如何向MVC控制器方法发送jQuery $.ajax() post请求的模型

时间:2022-05-12 13:44:43

In doing an auto-refresh using the following code, I assumed that when I do a post, the model will automatically sent to the controller:

在使用以下代码进行自动刷新时,我假设当我做一个帖子时,模型会自动发送给控制器:

$.ajax({
    url: '<%=Url.Action("ModelPage")%>',
    type: "POST",
    //data:  ??????
    success: function(result) {
        $("div#updatePane").html(result);
    },

    complete: function() {
    $('form').onsubmit({ preventDefault: function() { } });

    }
});

Every time there is a post, I need to increment the value attribute in the model:

每次有帖子,我都需要增加模型中的value属性:

public ActionResult Modelpage(MyModel model)
    {                   
        model.value = model.value + 1;

        return PartialView("ModelPartialView", this.ViewData);
    }

But the model is not passed to the controller when the page is posted with jQuery AJAX request. How can I send the model in the AJAX request?

但是,在使用jQuery AJAX请求发布页面时,不会将模型传递给控制器。如何在AJAX请求中发送模型?

7 个解决方案

#1


49  

The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.

简单的答案(在MVC 3中,甚至可能是2)是你不需要做任何特别的事情。

As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.

只要您的JSON参数与模型匹配,MVC就足够聪明,可以根据您提供的参数构造一个新对象。没有的参数只是默认的。

For example, the Javascript:

例如,Javascript:

var values = 
{
    "Name": "Chris",
    "Color": "Green"
}

$.post("@Url.Action("Update")",values,function(data)
{
    // do stuff;
});

The model:

模型:

public class UserModel
{
     public string Name { get;set; }
     public string Color { get;set; }
     public IEnumerable<string> Contacts { get;set; }
}

The controller:

控制器:

public ActionResult Update(UserModel model)
{
     // do something with the model

     return Json(new { success = true });
}

#2


25  

If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.

如果需要将完整的模型发送给控制器,首先需要将模型提供给javascript代码。

In our app, we do this with an extension method:

在我们的app中,我们使用扩展方法:

public static class JsonExtensions
{
    public static string ToJson(this Object obj)
    {
        return new JavaScriptSerializer().Serialize(obj);
    }
}

On the view, we use it to render the model:

在视图中,我们使用它来呈现模型:

<script type="javascript">
  var model = <%= Model.ToJson() %>
</script>

You can then pass the model variable into your $.ajax call.

然后,您可以将模型变量传递到您的$中。ajax调用。

#3


4  

I have an MVC page that submits JSON of selected values from a group of radio buttons.

我有一个MVC页面,它从一组单选按钮中提交选定值的JSON。

I use:

我使用:

var dataArray = $.makeArray($("input[type=radio]").serializeArray());

To make an array of their names and values. Then I convert it to JSON with:

创建它们的名称和值的数组。然后我将它转换成JSON:

var json = $.toJSON(dataArray)

and then post it with jQuery's ajax() to the MVC controller

然后使用jQuery的ajax()将其发布到MVC控制器

$.ajax({
url: "/Rounding.aspx/Round/" + $("#OfferId").val(),
type: 'POST',
dataType: 'html',
data: json, 
contentType: 'application/json; charset=utf-8',
beforeSend: doSubmitBeforeSend,
complete: doSubmitComplete,
success: doSubmitSuccess});

Which sends the data across as native JSON data.

它将数据作为原生JSON数据发送出去。

You can then capture the response stream and de-serialize it into the native C#/VB.net object and manipulate it in your controller.

然后可以捕获响应流并将其反序列化到本机c# /VB.net对象中,并在控制器中对其进行操作。

To automate this process in a lovely, low maintenance way, I advise reading this entry that spells out most of native, automatic JSON de-serialization quite well.

为了以一种可爱的、低维护的方式自动化这个过程,我建议您阅读这篇文章,它很好地阐明了大多数本机的、自动的JSON反序列化。

Match your JSON object to match your model and the linked process below should automatically deserialize the data into your controller. It's works wonderfully for me.

匹配JSON对象以匹配模型,下面的链接进程应该自动将数据反序列化到控制器中。这对我来说非常有效。

Article on MVC JSON deserialization

关于MVC JSON反序列化的文章

#4


3  

This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.

这可以通过构建一个javascript对象来匹配mvc模型来实现。javascript属性的名称必须与mvc模型完全匹配,否则自动绑定不会发生在post上。一旦在服务器端有了模型,就可以对其进行操作并将数据存储到数据库中。

I am achieving this either by a double click event on a grid row or click event on a button of some sort.

我通过在网格行上双击事件或者按某种按钮单击事件来实现这一点。

@model TestProject.Models.TestModel

<script>

function testButton_Click(){
  var javaModel ={
  ModelId: '@Model.TestId',
  CreatedDate: '@Model.CreatedDate.ToShortDateString()',
  TestDescription: '@Model.TestDescription',
  //Here I am using a Kendo editor and I want to bind the text value to my javascript
  //object. This may be different for you depending on what controls you use.
  TestStatus: ($('#StatusTextBox'))[0].value, 
  TestType: '@Model.TestType'
  }

  //Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox 
    //selected value. This puzzled me due to the conversion to Json object in the Ajax call. 
  //By parsing the Type to an int this worked.

  javaModel.TestType = parseInt(javaModel.TestType);

  $.ajax({
      //This is where you want to post to.
      url:'@Url.Action("TestModelUpdate","TestController")', 
      async:true,
      type:"POST",
      contentType: 'application/json',
      dataType:"json",
      data: JSON.stringify(javaModel)
  });
}
</script>


//This is your controller action on the server, and it will autobind your values 
//to the newTestModel on post.

[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
 TestModel.UpdateTestModel(newTestModel);
 return //do some return action;
}

#5


2  

I think you need to explicitly pass the data attribute. One way to do this is to use the data = $('#your-form-id').serialize();

我认为您需要显式地传递数据属性。其中一种方法是使用data = $('#your-form-id').serialize();

This post may be helpful. Post with jquery and ajax

这篇文章可能会有帮助。使用jquery和ajax发布

Have a look at the doc here.. Ajax serialize

看这里的医生。Ajax序列化

#6


1  

you can create a variable and send to ajax.

您可以创建一个变量并将其发送到ajax。

var m = { "Value": @Model.Value }

$.ajax({
    url: '<%=Url.Action("ModelPage")%>',
    type: "POST",
    data:  m,
    success: function(result) {
        $("div#updatePane").html(result);
    },

    complete: function() {
    $('form').onsubmit({ preventDefault: function() { } });

    }
});

All of model's field must bo ceated in m.

模型的所有场必须在m中终止。

#7


0  

In ajax call mention-

在ajax调用提到-

data:MakeModel(),

use the below function to bind data to model

使用下面的函数将数据绑定到模型

function MakeModel() {

    var MyModel = {};

    MyModel.value = $('#input element id').val() or your value;

    return JSON.stringify(MyModel);
}

Attach [HttpPost] attribute to your controller action

将[HttpPost]属性附加到控制器动作

on POST this data will get available

一旦发布,这些数据将会被获取

#1


49  

The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.

简单的答案(在MVC 3中,甚至可能是2)是你不需要做任何特别的事情。

As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.

只要您的JSON参数与模型匹配,MVC就足够聪明,可以根据您提供的参数构造一个新对象。没有的参数只是默认的。

For example, the Javascript:

例如,Javascript:

var values = 
{
    "Name": "Chris",
    "Color": "Green"
}

$.post("@Url.Action("Update")",values,function(data)
{
    // do stuff;
});

The model:

模型:

public class UserModel
{
     public string Name { get;set; }
     public string Color { get;set; }
     public IEnumerable<string> Contacts { get;set; }
}

The controller:

控制器:

public ActionResult Update(UserModel model)
{
     // do something with the model

     return Json(new { success = true });
}

#2


25  

If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.

如果需要将完整的模型发送给控制器,首先需要将模型提供给javascript代码。

In our app, we do this with an extension method:

在我们的app中,我们使用扩展方法:

public static class JsonExtensions
{
    public static string ToJson(this Object obj)
    {
        return new JavaScriptSerializer().Serialize(obj);
    }
}

On the view, we use it to render the model:

在视图中,我们使用它来呈现模型:

<script type="javascript">
  var model = <%= Model.ToJson() %>
</script>

You can then pass the model variable into your $.ajax call.

然后,您可以将模型变量传递到您的$中。ajax调用。

#3


4  

I have an MVC page that submits JSON of selected values from a group of radio buttons.

我有一个MVC页面,它从一组单选按钮中提交选定值的JSON。

I use:

我使用:

var dataArray = $.makeArray($("input[type=radio]").serializeArray());

To make an array of their names and values. Then I convert it to JSON with:

创建它们的名称和值的数组。然后我将它转换成JSON:

var json = $.toJSON(dataArray)

and then post it with jQuery's ajax() to the MVC controller

然后使用jQuery的ajax()将其发布到MVC控制器

$.ajax({
url: "/Rounding.aspx/Round/" + $("#OfferId").val(),
type: 'POST',
dataType: 'html',
data: json, 
contentType: 'application/json; charset=utf-8',
beforeSend: doSubmitBeforeSend,
complete: doSubmitComplete,
success: doSubmitSuccess});

Which sends the data across as native JSON data.

它将数据作为原生JSON数据发送出去。

You can then capture the response stream and de-serialize it into the native C#/VB.net object and manipulate it in your controller.

然后可以捕获响应流并将其反序列化到本机c# /VB.net对象中,并在控制器中对其进行操作。

To automate this process in a lovely, low maintenance way, I advise reading this entry that spells out most of native, automatic JSON de-serialization quite well.

为了以一种可爱的、低维护的方式自动化这个过程,我建议您阅读这篇文章,它很好地阐明了大多数本机的、自动的JSON反序列化。

Match your JSON object to match your model and the linked process below should automatically deserialize the data into your controller. It's works wonderfully for me.

匹配JSON对象以匹配模型,下面的链接进程应该自动将数据反序列化到控制器中。这对我来说非常有效。

Article on MVC JSON deserialization

关于MVC JSON反序列化的文章

#4


3  

This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.

这可以通过构建一个javascript对象来匹配mvc模型来实现。javascript属性的名称必须与mvc模型完全匹配,否则自动绑定不会发生在post上。一旦在服务器端有了模型,就可以对其进行操作并将数据存储到数据库中。

I am achieving this either by a double click event on a grid row or click event on a button of some sort.

我通过在网格行上双击事件或者按某种按钮单击事件来实现这一点。

@model TestProject.Models.TestModel

<script>

function testButton_Click(){
  var javaModel ={
  ModelId: '@Model.TestId',
  CreatedDate: '@Model.CreatedDate.ToShortDateString()',
  TestDescription: '@Model.TestDescription',
  //Here I am using a Kendo editor and I want to bind the text value to my javascript
  //object. This may be different for you depending on what controls you use.
  TestStatus: ($('#StatusTextBox'))[0].value, 
  TestType: '@Model.TestType'
  }

  //Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox 
    //selected value. This puzzled me due to the conversion to Json object in the Ajax call. 
  //By parsing the Type to an int this worked.

  javaModel.TestType = parseInt(javaModel.TestType);

  $.ajax({
      //This is where you want to post to.
      url:'@Url.Action("TestModelUpdate","TestController")', 
      async:true,
      type:"POST",
      contentType: 'application/json',
      dataType:"json",
      data: JSON.stringify(javaModel)
  });
}
</script>


//This is your controller action on the server, and it will autobind your values 
//to the newTestModel on post.

[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
 TestModel.UpdateTestModel(newTestModel);
 return //do some return action;
}

#5


2  

I think you need to explicitly pass the data attribute. One way to do this is to use the data = $('#your-form-id').serialize();

我认为您需要显式地传递数据属性。其中一种方法是使用data = $('#your-form-id').serialize();

This post may be helpful. Post with jquery and ajax

这篇文章可能会有帮助。使用jquery和ajax发布

Have a look at the doc here.. Ajax serialize

看这里的医生。Ajax序列化

#6


1  

you can create a variable and send to ajax.

您可以创建一个变量并将其发送到ajax。

var m = { "Value": @Model.Value }

$.ajax({
    url: '<%=Url.Action("ModelPage")%>',
    type: "POST",
    data:  m,
    success: function(result) {
        $("div#updatePane").html(result);
    },

    complete: function() {
    $('form').onsubmit({ preventDefault: function() { } });

    }
});

All of model's field must bo ceated in m.

模型的所有场必须在m中终止。

#7


0  

In ajax call mention-

在ajax调用提到-

data:MakeModel(),

use the below function to bind data to model

使用下面的函数将数据绑定到模型

function MakeModel() {

    var MyModel = {};

    MyModel.value = $('#input element id').val() or your value;

    return JSON.stringify(MyModel);
}

Attach [HttpPost] attribute to your controller action

将[HttpPost]属性附加到控制器动作

on POST this data will get available

一旦发布,这些数据将会被获取