且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Jquery/Ajax 将模型传递给控制器

更新时间:2023-02-25 17:29:42

看起来您的 IndexPartial 操作方法有一个参数,它是一个复杂对象.如果您要传递大量数据(复杂对象),***将您的操作方法转换为 HttpPost 操作方法并使用 jQuery post 发布数据到那个.GET 对查询字符串值有限制.

Looks like your IndexPartial action method has an argument which is a complex object. If you are passing a a lot of data (complex object), It might be a good idea to convert your action method to a HttpPost action method and use jQuery post to post data to that. GET has limitation on the query string value.

[HttpPost]
public PartialViewResult IndexPartial(DashboardViewModel m)
{
   //May be you want to pass the posted model to the parial view?
   return PartialView("_IndexPartial");
}

你的脚本应该是

var url = "@Url.Action("IndexPartial","YourControllerName")";

var model = { Name :"Shyju", Location:"Detroit"};

$.post(url, model, function(res){
   //res contains the markup returned by the partial view
   //You probably want to set that to some Div.
   $("#SomeDivToShowTheResult").html(res);
});

假设 NameLocationDashboardViewModel 类的属性,SomeDivToShowTheResult 是 div 中的 id您要加载来自局部视图的内容的页面.

Assuming Name and Location are properties of your DashboardViewModel class and SomeDivToShowTheResult is the id of a div in your page where you want to load the content coming from the partialview.

如果需要,您可以在 js 中构建更复杂的对象.只要您的结构与视图模型类匹配,模型绑定就会起作用

You can build more complex object in js if you want. Model binding will work as long as your structure matches with the viewmodel class

var model = { Name :"Shyju", 
              Location:"Detroit", 
              Interests : ["Code","Coffee","***"]
            };

$.ajax({
    type: "POST",
    data: JSON.stringify(model),
    url: url,
    contentType: "application/json"
}).done(function (res) {
    $("#SomeDivToShowTheResult").html(res);
});

要将上面的js模型转化为你的方法参数,你的View Model应该是这样的.

For the above js model to be transformed to your method parameter, Your View Model should be like this.

public class DashboardViewModel
{
  public string Name {set;get;}
  public string Location {set;get;}
  public List<string> Interests {set;get;}
}

并在您的操作方法中指定 [FromBody]

And in your action method, specify [FromBody]

[HttpPost]
public PartialViewResult IndexPartial([FromBody] DashboardViewModel m)
{
    return PartialView("_IndexPartial",m);
}