title: Ajax post in MVC 3 with multiple-form View
body: <p>I deleted my prior question dealing with the subject as the context has changed a bit and the problem is new.</p>
  
  <p>I have a single view now, with a single model. The view has 2 forms. Each form submits to its own action, each action uses a subset of the model data, uses the data to perform a search. The search results then are added to a property of the model and need to be rendered back to the view. I'm able to accomplish this all via a standard html post but this now needs to be an ajax post.</p>
  
  <p>Here is my ViewModel:</p>
  
  <pre><code>public sealed class SearchUsersViewModel {
  
      [Display(Name = "Last Name")]
      public string LastName { get; set; }
  
      [Display(Name = "Username")]
      public string Username { get; set; }
  
      [Display(Name = "Email Address")]
      public string EmailAddress { get; set; }
  
      [Display(Name = "Entity Type")]
      public byte EntityTypeID { get; set; }
  
      [Display(Name = "Search Name")]
      public string SearchField { get; set; }
  
      public IEnumerable&lt;SelectListDTO&gt; EntityTypes { get; set; }
  
      public IEnumerable&lt;UserEditViewModel&gt; Users { get; set; }
  
      [Display(Name = "Total Rows")]
      public int TotalRowCount { get; internal set; }
  
      public SearchUsersViewModel() {
          EntityTypes = LookupEntityTypeService.Instance.SelectList;
          Users = new List&lt;UserEditViewModel&gt;();
      }
  }
  </code></pre>
  
  <p>Here is my View:</p>
  
  <pre><code>@model SearchUsersViewModel
  
  &lt;div&gt;
      &lt;div class="SearchByUserDataTable"&gt;
          @using (Html.BeginForm("FilterByUserData", "Admin", FormMethod.Post, new {model = Model})) {
              @Html.ValidationSummary(true)
              &lt;table cellpadding="0" cellspacing="0" border="0"&gt;
                  &lt;tr style="height: 30px;"&gt;
                      &lt;td class="Header01"&gt;
                          User Search:
                      &lt;/td&gt;
                  &lt;/tr&gt;
              &lt;/table&gt;
              &lt;table cellpadding="0" cellspacing="0" border="0"&gt;
                  &lt;tr style="height: 20px;"&gt;
                      &lt;td class="Header02"&gt;
                          Search By User Information:
                      &lt;/td&gt;
                  &lt;/tr&gt;
              &lt;/table&gt;
              &lt;table cellpadding="0" cellspacing="0" border="0"&gt;
                  &lt;tr style="height: 1px;"&gt;
                      &lt;td class="ContentDividerHoriz_425"&gt;&lt;/td&gt;
                  &lt;/tr&gt;
              &lt;/table&gt;
              &lt;table id="searchByUserDataTable" cellpadding="0" cellspacing="0" border="0"&gt;
                  &lt;tr style="height: 26px;"&gt;
                      &lt;td class="leftColumn"&gt;
                          @Html.LabelFor(model =&gt; model.LastName):
                      &lt;/td&gt;
                      &lt;td class="rightColumn"&gt;
                          @Html.TextBoxFor(model =&gt; model.LastName, new { id = "lastNameSearchField", @class = "TextField_220" })
                      &lt;/td&gt;
                  &lt;/tr&gt;
                  &lt;tr style="height: 26px;"&gt;
                      &lt;td class="leftColumn"&gt;
                          @Html.LabelFor(model =&gt; model.Username):
                      &lt;/td&gt;
                      &lt;td class="rightColumn"&gt;
                          @Html.TextBoxFor(model =&gt; model.Username, new { id = "userNameSearchField", @class = "TextField_220" })
                      &lt;/td&gt;
                  &lt;/tr&gt;
                  &lt;tr style="height: 26px;"&gt;
                      &lt;td class="leftColumn"&gt;
                          @Html.LabelFor(model =&gt; model.EmailAddress):
                      &lt;/td&gt;
                      &lt;td class="rightColumn"&gt;
                          @Html.TextBoxFor(model =&gt; model.EmailAddress, new { id = "emailAddressSearchField", @class = "TextField_220" })
                      &lt;/td&gt;
                  &lt;/tr&gt;
              &lt;/table&gt;
              &lt;table cellpadding="0" cellspacing="0" border="0"&gt;
                  &lt;tr&gt;
                      &lt;td id="filterByUserError" style="width: 375px;"&gt;&lt;/td&gt;
                      &lt;td align="right" style="width: 50px; padding-right: 75px;"&gt;
                          &lt;div&gt;
                              &lt;input id="filterByUserButton" type="submit" value="Search" /&gt;
                          &lt;/div&gt;
                      &lt;/td&gt;
                  &lt;/tr&gt;
              &lt;/table&gt;
          }
      &lt;/div&gt;
  
      &lt;div class="SearchByEntityDataTable"&gt;
          @using (Html.BeginForm("FilterByEntityData", "Admin", FormMethod.Post, new { model = Model })) { 
              &lt;table cellpadding="0" cellspacing="0" border="0"&gt;
                  &lt;tr style="height: 28px;"&gt;
                      &lt;td style="width: 425px;"&gt;&lt;/td&gt;
                  &lt;/tr&gt;
              &lt;/table&gt;
              &lt;table cellpadding="0" cellspacing="0" border="0"&gt;
                  &lt;tr style="height: 20px;"&gt;
                      &lt;td class="Header02"&gt;
                          Search By Entity Information:
                      &lt;/td&gt;
                  &lt;/tr&gt;
              &lt;/table&gt;
              &lt;table cellpadding="0" cellspacing="0" border="0"&gt;
                  &lt;tr style="height: 1px;"&gt;
                      &lt;td class="ContentDividerHoriz_425"&gt;&lt;/td&gt;
                  &lt;/tr&gt;
              &lt;/table&gt;
              &lt;table id="searchByEntityDataTable" cellpadding="0" cellspacing="0" border="0"&gt;
                  &lt;tr style="height: 26px;"&gt;
                      &lt;td class="leftColumn"&gt;
                          @Html.LabelFor(model =&gt; model.EntityTypeID):
                      &lt;/td&gt;
                      &lt;td class="rightColumn"&gt;
                          @Html.DropDownListFor(model =&gt; model.EntityTypeID, new SelectList(Model.EntityTypes, "ID", "Name"), new { id = "entityTypeDropDown", @class = "DropDown_220" })
                      &lt;/td&gt;
                  &lt;/tr&gt;
                  &lt;tr style="height: 26px;"&gt;
                      &lt;td class="leftColumn"&gt;
                          @Html.LabelFor(model =&gt; model.SearchField, new { id = "entityTypeSearchLabel"}):
                      &lt;/td&gt;
                      &lt;td class="rightColumn"&gt;
                          @Html.TextBoxFor(model =&gt; model.SearchField, new { id = "entityTypeSearchField", @class = "ui-widget TextField_220" })
                      &lt;/td&gt;
                  &lt;/tr&gt;
                  &lt;tr style="height: 26px;"&gt;
                      &lt;td class="leftColumn"&gt;&lt;/td&gt;
                      &lt;td class="rightColumn"&gt;&lt;/td&gt;
                  &lt;/tr&gt;
              &lt;/table&gt;
              &lt;table cellpadding="0" cellspacing="0" border="0"&gt;
                  &lt;tr&gt;
                      &lt;td id="filterByEntityError" style="width: 375px;"&gt;&lt;/td&gt;
                      &lt;td align="right" style="width: 50px; padding-right: 75px;"&gt;
                          &lt;div&gt;
                              &lt;input type="submit" value="Search" /&gt;
                          &lt;/div&gt;
                      &lt;/td&gt;
                  &lt;/tr&gt;
              &lt;/table&gt;
          }
      &lt;/div&gt;
  
      &lt;div id="searchResults"&gt;
          @(Html.Telerik().Grid(Model.Users)
              .Name("Users").TableHtmlAttributes(new { style = "width: 870px;"})
              .Columns(columns =&gt; {
                  columns.Bound(o =&gt; o.EntityTypeName).Title("Entity Type");
                  columns.Bound(o =&gt; o.FirstName).Title("First Name");
                  columns.Bound(o =&gt; o.LastName).Title("Last Name");
                  columns.Bound(o =&gt; o.Username).Title("Username");
                  columns.Template(
                      @&lt;text&gt;
                          &lt;a href="mailto:@item.EmailAddress" target="blank"&gt;@item.EmailAddress&lt;/a&gt;
                      &lt;/text&gt;).Title("Email").HtmlAttributes(new { style = "text-align: center" }).HeaderHtmlAttributes(new { style = "text-align: center" });
                  columns.Template(
                      @&lt;text&gt;
                          &lt;div class="ActionIcon_ResendInvitationOn" title="Resend Invitation" onclick="location.href='@Url.Action("ResendInvitation", "Admin", new { entityTypeID = item.EntityTypeID, emailAddress = item.EmailAddress })'"&gt;&lt;/div&gt; 
                          @{
                              if (item.IsApproved) {
                                  &lt;div class="ActionIcon_AccountStatusOn" title="Disable Account" onclick="setApprovalStatus('@item.Username', false);"&gt;&lt;/div&gt; 
                              }
                              else {
                                  &lt;div class="ActionIcon_AccountStatusOn" title="Enable Account" onclick="setApprovalStatus('@item.Username', true);"&gt;&lt;/div&gt; 
                              }
                          }
                          @{
                              if (item.IsLockedOut) {
                                  &lt;div class="ActionIcon_ResetPasswordOn" title="Unlock Account" onclick="unlockAccount('@item.Username')"&gt;&lt;/div&gt; 
                              }
                              &lt;div class="ActionIcon_ResetPasswordOn" title="Reset Password"  onclick="resetPassword('@item.Username')"&gt;&lt;/div&gt; 
                          }
                          &lt;div class="ActionIcon_EditOn" title="Edit User" onclick="location.href='@Url.Action("Edit", "Admin", new { id = item.MembershipID, username = item.Username })'"&gt;&lt;/div&gt;
                      &lt;/text&gt;).Title("Actions");
                  columns.Bound(o =&gt; o.RowNumber).Hidden(true);
                  columns.Bound(o =&gt; o.MembershipID).Hidden(true);
                  columns.Bound(o =&gt; o.EntityTypeID).Hidden(true);
              })
              .Pageable(paging =&gt; paging.PageSize(10))
              .Sortable()
          )
          &lt;span&gt;Total Rows: &lt;/span&gt; @Html.DisplayFor(model =&gt; Model.TotalRowCount)
  
          &lt;p&gt;
              @Html.ActionLink("Create New User", "Create", "Invitation")
          &lt;/p&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>I have used this view with this line as the BeginForm:</p>
  
  <pre><code>@using (Html.BeginForm("FilterByUserData", "Admin", FormMethod.Post, new {model = Model})) 
  </code></pre>
  
  <p>And using this:</p>
  
  <pre><code> @using (Html.BeginForm())
  </code></pre>
  
  <p>with this Ajax script</p>
  
  <pre><code>$('#filterByUserButton').click(function () {
      $.ajax({
          url: '/Admin/FilterByUserData',
          type: 'POST',
          success: function (result) {
              alert(result);
          }
      });
  });
  </code></pre>
  
  <p>With the first method using the HTML post it works fine but I need to use the ajax functionality so the 2nd method is my trouble</p>
  
  <p>1) Using the ajax call the model being posted to the action contains all Null values in the text fields instead of the values I'm entering on the form. The model posts fine using the HTML method</p>
  
  <p>2) Even if I can get the model to post correctly so that I have values to search with, how do I return the data to the grid and how do I show model errors when the validation fails instead of sending the result to the UpdateTargetID? </p>
  
  <p>3) Being able to have both forms submit to the controller and have the same results back to the view, a search result</p>
  
  <p>It seems I can only have 1 UpdateTarget - which is fine if you never have errors...but the behavior is bad, I need to show the validation errors on the field just the same as if this was a synchronous call. So the error result coming from the action would need to have it's own target.</p>
  
  <p>I came up with this Ajax call that works fine with actions that don't need to return data, just a success or error message. Each gets loaded into its own div.</p>
  
  <pre><code>$(function () {
      $('form').submit(function () {
          if ($(this).valid()) {
              $.ajax({
                  url: this.action,
                  type: this.method,
                  data: $(this).serialize(),
                  success: function (result) {
                      if (result.toString().indexOf("Success") == -1) {
                          $('#successDiv').hide();
                          $('#errorDiv').html('');
                          $('#errorDiv').fadeIn(100).append($('&lt;ul /&gt;').append(result));
                      }
                      else {
                          $('#errorDiv').hide();
                          $('#successDiv').fadeIn(1000).html(result).fadeOut(6000);
                      }
                  }
              });
          }
          return false;
      });
  });
  </code></pre>
  
  <p>These are the actions that process the search (The FilterByUserData action is different as I was trying to work out how to get a proper result back, I don't yet have it returning data properly.</p>
  
  <pre><code>    public ActionResult Search() {
          var model = new SearchUsersViewModel();
          return View(model);
      }
  
      [HttpPost]
      public ActionResult FilterByUserData(SearchUsersViewModel model) {
          var result = string.Empty;
          if (model.LastName != null || model.Username != null || model.EmailAddress != null) {
              var listOfMatchingUsers = SearchUserService.SearchByUserData(model.LastName, model.Username, model.EmailAddress);
              model = PrepareResultsModel(listOfMatchingUsers, model);
          }
          else {
              ModelState.AddModelError("", "Last Name, Username or Email Address must be entered for search");
          }
          if (ModelState.IsValid)
              result = "Success: Thanks for your submission: " + model.Username;
          else {
              result = ModelState.SelectMany(item =&gt; item.Value.Errors).Aggregate(result, (current, error) =&gt; current + error.ErrorMessage);
          }
          return Content(result, "text/html");
      }
  
      [HttpPost]
      public ActionResult FilterByEntityData(SearchUsersViewModel model) {
          if(model.EntityTypeID &gt; 0 &amp;&amp;  model.SearchField != null) {
              var listOfMatchingUsers = SearchUserService.SearchByEntityData(model.EntityTypeID, model.SearchField);
              model = PrepareResultsModel(listOfMatchingUsers, model);
          }
          else {
              var entityType = string.Empty;
              if(model.EntityTypeID == 2) entityType = "Lender";
              if (model.EntityTypeID == 3) entityType = "School";
              ModelState.AddModelError("", entityType + " name must be entered for search");
          }
          return View("Search", model);
      }
  
      private SearchUsersViewModel PrepareResultsModel(ICollection&lt;SearchUserResultsDTO&gt; listOfMatchingUsers, SearchUsersViewModel model) {
          if (listOfMatchingUsers.Count != 0) {
              model.Users = listOfMatchingUsers.Select(item =&gt; new UserEditViewModel(item)).ToList();
              model.TotalRowCount = model.Users.Count();
          }
          return model;
      }
  </code></pre>
  
  <p>How can I get the model for the ajax post to make it to my action? and how do I get a proper model back so that my grid has the results? and if there is an error how can I get that shown in a similar manner to validationsummary?</p>
  
  <p><strong>Update:</strong> for @Shyju
  I tried what you suggested trying to incorporate your example into my code but the values of the properties of the model are still null and are not being set. This is what I did in my ajax function, note that it is different than your form.post method:</p>
  
  <pre><code>$('#filterByUserButton').click(function () {
      $.ajax({
          url: '/Admin/FilterByUserData',
          type: 'POST',
          data: {LastName : $('#LastName').val(), Username : $('#Username').val(), EmailAddress : $('#EmailAddress').val()},
          success: function (result) {
              processResult(result);
          }
      });
  });
  </code></pre>
  
  <p>I also tried this:</p>
  
  <pre><code>$('form').submit(function() {
      alert("submitting");
      $.post('@Url.Action("FilterByUserData","Admin")', { LastName: $("#LastName").val(), UserName: $("#Username").val(), EmailAddress: $("#EmailAddress").val() },
          function(data) {
              alert(data);
      });
  });
  </code></pre>
  
  <p>The page flashes and the first alert is it but it never hits the 2nd alert and never hits the controller so it looks like it's not even truly posting.
  I also tried this but it also does not hit the controller action:</p>
  
  <pre><code>$('#filterByUserButton').click(function () {
      alert("submitting");
      $.ajax({
          url: '/Admin/FilterByUserData',
          type: 'POST',
          data: {LastName : $('#LastName').val(), Username : $('#Username').val(), EmailAddress : $('#EmailAddress').val()},
          success: function (result) {
              alert(result);
              processResult(result);
          }
      });
  });
  </code></pre>
  
  <p>I also tried the above with the data: line omitted and it will hit my controller action but again, the model being sent has null values in the properties. The model isn't null, just the property values. I do have values in the dropdown list properties of the model, the EntityTypes still show 4 values. So there's something about posting that form but the form values are not making it into the model properties.</p>
  
  <p><strong>Update 2</strong></p>
  
  <p>@Shyju I'm using your ajax code like so:</p>
  
  <pre><code>$(function () {
      $('#SearchByUserForm').submit(function () {
          $.post('@Url.Action("FilterByUserData", "Admin")', { LastName: $("#LastName").val(), UserName: $("#UserName").val(), EmailAddress: $("#EmailAddress").val() },
          function (data) {
              alert(data);
          });
          return false;
      });
  });
  </code></pre>
  
  <p>I can step thru this after hitting the submit button but it fails to hit the post action of my controller. I looked at the HTML rendered for the form and this is what I see.. which is incorrect:</p>
  
  <pre><code>&lt;form action="/Admin/Search/SearchByUserForm" method="post"&gt;         
  </code></pre>
  
  <p>As you can see the POST action here is wrong. The Controller is correct but the rest is wrong. It should be posting to /Admin/FilterByUserData. I'm sure this is just a syntactical mess that I'm in and I'm just not sure what I'm doing wrong. In a standard form I would do this:</p>
  
  <pre><code>@using (Html.BeginForm("FilterByUserData", "Admin", FormMethod.Post, new { model = Model })) { 
  </code></pre>
  
  <p>Which works correctly. But I can't combine this form signature with the URL action post from your Ajax code. I tried just leaving the form stark with only the ID but I get the problem I stated above:</p>
  
  <pre><code>@using (Html.BeginForm(new {@id = "SearchByUserForm"})) {
  </code></pre>
  
  <p>I think this problem comes about from the fact that my view is rendered by hitting the Search action of my controller, so the URL is /Admin/Search but the forms on the view need to post to /Admin/FilterByUserData and /Admin/FilterByEntityData. Like I said above if I explicitly create the Html.BeginFrom with the right signature then it works,, but it's just not Ajax</p>
  
  <p><strong>Update 3</strong></p>
  
  <p>@Shyju</p>
  
  <p>I got it working, the problem was definitely the Form signature, I modified it and I can hit my controller action successfully and also the data is being passed in! Thanks for all your help!</p>
  
  <p>This is what got it working:</p>
  
  <pre><code>@using (Html.BeginForm(new {id = "SearchByUserForm", @controller = "Admin", @action = "FilterByUserData"})) {
  </code></pre>