gpt4 book ai didi

asp.net-mvc - 使用 Jquery/Ajax 将模型传递到 Controller

转载 作者:行者123 更新时间:2023-12-02 01:42:29 27 4
gpt4 key购买 nike

我正在尝试使用 JQuery/Ajax 将我的模型传递给 Controller ​​,我不确定如何正确执行此操作。到目前为止,我已经尝试使用 Url.Action 但模型是空白的。

注意:stackoverflow 上的重复线程似乎都没有使用 ASP.NET 5 MVC 6 来解决。

查看:

$("#inpDateCompleted").change(function () {
var url = '@(Url.Action("IndexPartial", "DashBoard", Model, null))';
$("#DailyInvoiceItems").load(url);
});

Controller :

 [HttpGet]
public PartialViewResult IndexPartial(DashBoardViewModel m)
{
// Do stuff with my model
return PartialView("_IndexPartial");
}

最佳答案

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

[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您要在其中加载来自分部 View 的内容的页面。

发送复杂对象?

如果你愿意,你可以在js中构建更复杂的对象。只要您的结构与 View 模型类匹配,模型绑定(bind)就会起作用

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

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

为了将上面的js模型转换为你的方法参数,你的 View 模型应该是这样的。

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

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

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

关于asp.net-mvc - 使用 Jquery/Ajax 将模型传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33947882/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com