Mail form with jQgrid in ASP.Net MVC 3

I tried to publish my search form in the controller and load the json result in jQGrid. But I always get null in the controller.

public class SearchViewModel { public string Name{get;set;} public string Location{get;set;} public string EmployeeId{get;set;} } @model UI.ViewModel.SearchViewModel <div id="search-panel"> @{Html.EnableClientValidation();} @using (Html.BeginForm("Search", "Home", FormMethod.Post, new { id = "search-form" })) { @Html.AntiForgeryToken() <div class="formfield-container"> <label> <span class="column">Name:</span> @Html.TextBoxFor(m => m.Name) </label> </div> <div class="formfield-container"> <label> <span class="column">Emp Id:</span> @Html.TextBoxFor(m => m.EmployeeId) </label> </div> <div class="formfield-container"> <label> <span class="column">Location:</span> @Html.TextBoxFor(m => m.Location) </label> </div> } 

This is my jQGrid code

 jQuery("#list").jqGrid({ //start url: 'Home/Search', datatype: "json", postData: { viewModel: function () { return $("#search-form").serialize(); } }, mtype: "POST", //etc.. other config goes }); 

Here is my controller code

  [HttpPost] public JsonResult Search(SearchViewModel viewModel) { //viewModel parameter is always null var searchResult=//getting records from DB and preparing structure for jQGrid //Request["PostData"] gives json array sting of my form field and its value Json(searchResult); } 

I also tried this post. jQgrid placement of user data at boot . But the SearchViewModel is NULL.

But I see this in the Requst ["PostData"] value as the JSON string of my form field name and its value. This means that my form is successfully submitted to the server with data in the form of JSON sting. How can I directly get these JSON string to direct a strongly typed model .

But I could see that Request.Params ["viewModel"] contains details of the form element

Can anyone help get my form as a view model? or do I need to write my own custom binder?

0
source share
1 answer

We use a small function to serialize the form into an object for this:

 $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }; 

And then in jQgrid:

 jQuery("#list").jqGrid({ ... beforeRequest: GridOnBeforeRequest, ... }); function GridOnBeforeRequest() { var data = $("#search-form").serializeObject(); $("#list").jqGrid('setGridParam', { postData: data }); } 

And then update the grid:

 $("#list").trigger('reloadGrid'); 
0
source

Source: https://habr.com/ru/post/918041/


All Articles