0

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.

3
  • You need to serialise your model to JSON if you want to use it in javascript. Using Json.net you would use something like @JsonConvert.SerializeObject(model) Commented Sep 3, 2015 at 13:37
  • I am trying Alex's answer below same as yours, but I am having Compilation Error with JsonConvert Commented Sep 3, 2015 at 13:50
  • You need to get the Newtonsoft.Json nuget package for the JsonConvert to be recognized Commented Sep 3, 2015 at 13:58

3 Answers 3

0

When using fnServerParams you use aoData.push to send custom parameters to the server. I'm not sure about passing the entire model as a single parameter, but you can do it like this:

aoData.push({ "name": "customParam1", "value": $('#param1').val() });
aoData.push({ "name": "customParam2", "value": $('#param2').val() });

where param1 and param2 are model properties retrieved from jQuery selectors.

Your controller method needs to retrieve these parameters from the querystring. Something like this:

Create a model that represents the custom parameters (this would basically replicate MyViewModel in your example):

public class MyCustomParamModel
{
    public string customParam1 { get; set; }
    public string customParam2 { get; set; }
}

In the controller, parse the querystring, get the custom params and assign them to your model

public JsonResult GetResult(JQueryDataTableParamModel param)
{
    NameValueCollection qs = HttpUtility.ParseQueryString(Request.QueryString.ToString());

    var model = new MyCustomParamModel
    {
        customParam1 = qs["customParam1"],
        customParam2 = qs["customParam2"],
    }

Now you have your model data in the controller and you can do whatever you want with it.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I get the point here. But what if I have a property of MyCustomParamModel as DataTable? How can I do that? Let's say MyCustomParamModel.customParam1 is a datatable?
I think you'd have to pass it as an array, or stringify it somehow, I'm not really sure how or why you'd do this. Can you explain what you're trying to do?
0

As long as you pass the json object with the same properties as your model, you should be home safe, eg:

Model:

public class Language
    {
        public int ID { get; set; }
        public string Language1{ get; set; }
        public string Language2 { get; set; }
    }

Ajax:

$.ajax({
            url: '@Url.Action("Action", "Controller")',
            type: "POST",
            contentType: 'application/json',
            data: JSON.stringify({
                ID: 1,
                Language1: "English",
                Language2: "German",
                         }),
            dataType: 'json',


            success: function (data) {
                alert(data)
            }
        });

Comments

0

You can serialize your model with @Html.Raw(JsonConvert.SerializeObject(Model)) so your function will look like:

"fnServerParams": function (aaData) {

            aaData.push({ name: "viewModel", value: @Html.Raw(JsonConvert.SerializeObject(Model)) });
        },

4 Comments

Thanks Alex for your time on checking my problem, and how can I catch that with my controller GetResult() ?
You don't need to do anything special. MVC model binder will resolve this model. Just use your viewModel object in the method. It will have all the values that you passed from client
JsonConvert returns Compilation Error from my end. :(
You mean JsonConvert.SerializeObject(Model) returns a compilation error?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.