Reputation: 747
I have the following model class:
[Serializable]
public class SearchHomeModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Company { get; set; }
public string Title { get; set; }
}
I have the following controller code:
public ActionResult DataTableUserList(SearchHomeModel search, UserListType type, int iDisplayStart, int iDisplayLength, string sEcho)
and the following client part:
var search = {};
search.FirstName = 'aa';
search.LastName = 'bb';
search.Company = 'kkk';
search.Title = 'aaaawww';
fnServerData: function (sSource, aoData, fnCallback) {
aoData.push({ "name": "type", "value": "All" });
aoData.push({ "name": "search", "value": search });
$.ajax({
dataType: 'json',
type: "POST",
url: sSource,
data: aoData,
but I look at debugger on server-side I see that type="All" (it's correct), but search is null. Why and how to pass data to search object from ajax?
Upvotes: 0
Views: 356
Reputation: 3054
You may or may not find this useful, but I did this so I could directly pass JSON back and forth from the controller. I had come across this approach HERE while playing around with Knockout.js.
I created this attribute
public class FromJsonAttribute : CustomModelBinderAttribute
{
private readonly static JavaScriptSerializer serializer = new JavaScriptSerializer();
public override IModelBinder GetBinder()
{
return new JsonModelBinder();
}
private class JsonModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
if (string.IsNullOrEmpty(stringified))
return null;
return serializer.Deserialize(stringified, bindingContext.ModelType);
}
}
}
This is my controller code:
[HttpPost]
public ActionResult Gifts([FromJson] List<GiftModel> gifts, [FromJson] string guid)
{
}
Upvotes: 1