简体   繁体   English

ASP.NET MVC使用Ajax将整个模型传递给控制器

[英]ASP.NET MVC passing whole model to controller using ajax

How can I pass view's Model to controller using ajax? 如何使用Ajax将视图的模型传递给控制器​​? Please see JS function CreateTable() below: 请参见下面的JS函数CreateTable():

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: 这是datatables.net处理的ajax部分:

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. 我的朋友告诉我,我也可以将整个模型从ajax传递给我的控制器,但是我不确定该怎么做。 Please advise what is the better way to implement this. 请告知实现此目的的更好方法是什么。 Thank you. 谢谢。

You can serialize your model with @Html.Raw(JsonConvert.SerializeObject(Model)) so your function will look like: 您可以使用@Html.Raw(JsonConvert.SerializeObject(Model))序列化模型,这样您的函数将如下所示:

"fnServerParams": function (aaData) {

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

As long as you pass the json object with the same properties as your model, you should be home safe, eg: 只要您传递与模型具有相同属性的json对象,就应该可以安全使用,例如:

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)
            }
        });

When using fnServerParams you use aoData.push to send custom parameters to the server. 使用fnServerParams时,请使用aoData.push将自定义参数发送到服务器。 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. 其中param1param2是从jQuery选择器检索的模型属性。

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): 创建一个代表自定义参数的模型(这将在您的示例中基本上复制MyViewModel ):

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. 现在,您已将模型数据存储在控制器中,并且可以使用它进行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM