How can I pass view's Model to controller using ajax? Please see JS function CreateTable() below:
My Controller:
public ActionResult Index()
{
var viewModel = new MyViewModel();
return View(viewModel);
}
[HttpPost]
public ActionResult Index(MyViewModel viewModel)
{
//CODE FOR GETTING STUFF HERE
return View(viewModel);
}
public JsonResult GetResult(JQueryDataTableParamModel param, MyViewModel viewModel)
{
//CODE FOR GETTING STUFF HERE
return Json(new
{
sEcho = param.sEcho,
aaData = viewModel.Data,
iTotalRecords = viewModel.Data.Rows.Count,
iTotalDisplayRecords = viewModel.DisplayRecords
}, JsonRequestBehavior.AllowGet);
}
Here's the ajax part for the datatables.net processing:
function CreateTable() {
var table = $('#dataTable').DataTable({
"deferRender": true,
"bServerSide": true,
"sAjaxSource": "@Url.Action("GetResult")",
"fnServerParams": function (aaData) {
//here's my problem: HOW CAN I PUSH MY WHOLE MODEL HERE?
aaData.push({ "name": "MyViewModel", "value": "@Model" });
},
"sPaginationType": "simple_numbers",
"bProcessing": true,
"oLanguage": { "sProcessing": "Loading..." },
"aoColumns": [
{ "sName": "Col1" },
{ "sName": "Col2" },
{ "sName": "Col3" },
{ "sName": "Col3" },
{ "sName": "Col4" },
{ "sName": "Col5" }
]
});
}
My friend told me that I can also pass the whole Model from ajax to my controller but I'm not sure how to do that. Please advise what is the better way to implement this. Thank you.
@JsonConvert.SerializeObject(model)Newtonsoft.Jsonnuget package for the JsonConvert to be recognized