Partial view and AJAX Form with MVC3 Razor


One of the great advantages of using MVC is the partial view. In real life projects, sooner or later you come across the situations where you need to reuse the already developed thing. For this, in asp.net web forms, Web user control is there. In MVC, It is Partial view.  Partial view can be used as a plug and play user control for reusability. For updating a part of the page, we can use AJAX Form.

By using the combination of AJAX form and partial view, we can create ajaxify web application in MVC.

It is important to think that where and how you use partial view in your project. The proper structure of folder is also important while designing partial view. In ASP.net MVC application, all views are stored inside the "View" folder. You can keep your partial views in a special folder called "Shared" which is by default provided by the MVC when  you create a new web project of MVC type. By putting your partial view in "Shared" folder will make your things easy. The MVC engine look into this folder for partial view at the render time. But, you can also create your own folder, or keep partial view in the folder of your controller inside "view" folder.  Again, that is upto you and the architecture  of your web project.

I would recommends that you create a separate folder ("UserControls" for example) in "Views" folder and keep all your partial view there.

Now, comes to the main point...Lets see in action how to implement the partial view and calling it using AJAXForm.

Important: You need to include "jquery.unobtrusive-ajax.min.js" in order to work with AJAXForm.


Open visual studio 2010, and Create new MVC3 project with Razor  and select "Internet application" which by default provide home and account controller with relevant views.




You can see the default architecture of website. I have created following partial views:

_Layout.cshtml
  • This view is provided by the MVC application project.   This view works in similar fashion as of ASP.Net Master page(if you are familiar). We will load all our partial view inside this view.

Header.cshtml
  • This view will use a header control which will render at the top of the page inside. It contains  a  Text box and a "Search" button which is used to search an item and display it in the body with Ajax and partial render. This partial view will be render into _Layout.cshtml

Body.cshtml
  •  This is the main view, where main content of your website will be render. ex. a user regirstration form.
Footer.cshtml
  • It is used to display the footer information 
_search.cshtml
  •  this will display the search results based on the criteria.




Header.cshtml

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript">script>
<div id="header">
    <div id="title">
        <h1>
            My MVC Applicationh1>
    div>
       
    @using (Ajax.BeginForm("Search", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "searchResults" }))
    {
        <div>
            @Html.TextBox("search")
            <input type="submit" value="Search" id="searchbutton" />
        div>
    }
div>




This view contains the “search” text and a submit button called “Search” which will post back the form but in Ajax manner. You can see the line “Ajax.BeginForm” which is used to post data to the form with ajax call.
Ajax.BeginForm has following options:
Viewname – Name of view to render 
Controller - Name of the controller of which the view is belongs. I didn't mentioned any controller name as the "_search" partial view is inside the "Shared" folder. So the Razor engine will automatically find it. 
AJAXOptions() – It has various options for setting up AJAX call such as HttpMethod, updateTargetId as display in above code.   The UpdateTargetId determines which controls needs to update with the results of AJAX call. In this case, it will update the div called “searchResults” which is in “Body.cshtml” view.
Apart from this AJAXOptions it has other option to define events like BeforeRequest, Complete, Failure etc.  



Body.cshtml

@model PartialView.Models.UserModel
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript">script>


    <div id="searchResults">div>


 The "Body.cshtml" does nothing. It is working like a container ("searchResults" in this case) where result of AJAX call will be rendered. 


_search.cshtml

@model PartialView.Models.UserModel
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript">script>
<div id="company">
    @using (Ajax.BeginForm("Search", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "searchResults" }))
    {
        <div>
            @Html.RadioButton("company", 1, false, new { onclick = "SubmitForm();" }) All
            <br />
            @Html.RadioButton("company", 2, true, new {  onclick = "SubmitForm();" }) Active
            <br />
            @Html.RadioButton("company", 3, false, new {onclick = "SubmitForm();" }) inactive
            <br />
        div>
        <table>
            <thead>
                <tr>
                    <td>
                        company name
                    td>
                    <td>
                        Company code
                    td>
                tr>
            thead>
            @foreach (var item in Model.companyList)
            {
                <tr>
                    <td>@item.companyName
                    td>
                    <td>@item.companyCode
                    td>
                tr>
            }
        table>
    }
div>



<script type="text/javascript" language="javascript">
    function SubmitForm()
    {
        $("form").trigger('submit')
        return false;
    }
script>


_search view is the main view which will generate the result based on the specified search criteria.  It will display the list of searched companies in table format. 

You have observed here the javascript function "submitForm". It has  a line called "$("form").trigger('submit')
As we want to post the form on the radiobutton click event, we need to include this line. 

You might have a question in your mind that why I should not used $("form").submit(); method of Jquery.  This is because when a partial view is rendered, it is dynamic. So MVC/Jquery engine can't find the form name to submit.   for that you need to use this line.


Controller:
[HttpPost]
public ActionResult Search(string company)
{
  UserModel search = new UserModel();
  search.SearchEntities();
  if(company !=null)
  {
     selectCompanyOption = company;
  }

  if (selectCompanyOption == "2")
  {
       search.companyList = search.companyList.Where(c => c.isActive == true).ToList();
  }
  else if (selectCompanyOption == "3")
  {
      search.companyList = search.companyList.Where(c => c.isActive == false).ToList();
  }

  return PartialView("_search", search);
}


The controller contains an action method called “Search” which will get the list of companies based on the specified criteria. It will return a Partial view “_search” with the company list data.  This method defines how to render Partial view from the controller.


_Layout.cshtml

DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Titletitle>
  
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript">script>
   
head>
<body>
    <div class="page">
        @Html.Partial("Header")
        <div id="main">
           
        @Html.Partial("Body")


            @RenderBody()
        div>
        <div id="footer">
        div>
    div>
   
body>
html>



 
This view is provided by MVC web application project. If you can observe, I have render "Header" and "Body" as partial.
All this work without post backs. You can use this approach for your MVC based web application. All your views will be loaded into Body partially or fully via AJAX call. So you can avoid redirect or full post back mechanism by using this technique. 
Hope, this blog helps you creation/implementation  of   AJAX and partial view in MVC 3 Razor.


Have a happy coding !!!! :)

Comments

Popular posts from this blog

Fetching Address book AKA Contact information from Device using Xamarin.Forms

Hyperlink label in Xamarin.Forms