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

ASP.NET MVC passing whole model to controller using ajax

如何使用 ajax 将视图的模型传递给控制器​​?请看下面的 JS 函数 CreateTable():

我的控制器:

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

这是 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" }
        ]
    });
}

我的朋友告诉我,我还可以将整个模型从 ajax 传递到我的控制器,但我不确定该怎么做。请告知什么是更好的实现方法。谢谢你。

您可以使用 @Html.Raw(JsonConvert.SerializeObject(Model)) 序列化您的模型,这样您的函数将如下所示:

"fnServerParams": function (aaData) {

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

只要传递与模型属性相同的json对象,就应该安全到家了,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)
            }
        });

当使用 fnServerParams 时,您使用 aoData.push 将自定义参数发送到服务器。我不确定是否将整个模型作为单个参数传递,但您可以这样做:

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

其中 param1param2 是从 jQuery 选择器中检索到的模型属性。

您的控制器方法需要从查询字符串中检索这些参数。像这样:

创建一个表示自定义参数的模型(在您的示例中这基本上会复制 MyViewModel):

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

在控制器中,解析查询字符串,获取自定义参数并将它们分配给您的模型

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

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

现在你在控制器中有了模型数据,你可以用它做任何你想做的事。