使用 Jquery/Ajax 将模型传递给控制器
Pass Model To Controller using Jquery/Ajax
我正在尝试使用 JQuery/Ajax 将我的模型传递给控制器,但我不确定如何正确执行此操作。到目前为止,我已经尝试使用 Url.Action
,但模型是空白的。
注意:Whosebug 上的 none 个重复线程似乎使用 ASP.NET 5 MVC 6.
来解决
查看:
$("#inpDateCompleted").change(function () {
var url = '@(Url.Action("IndexPartial", "DashBoard", Model, null))';
$("#DailyInvoiceItems").load(url);
});
控制器:
[HttpGet]
public PartialViewResult IndexPartial(DashBoardViewModel m)
{
// Do stuff with my model
return PartialView("_IndexPartial");
}
看起来您的 IndexPartial
操作方法有一个参数,它是一个复杂的对象。如果您传递大量数据(复杂对象),将您的操作方法转换为 HttpPost
操作方法并使用 jQuery post
到 [=41= 可能是个好主意] 数据到那个。 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);
});
假设 Name
和 Location
是您 DashboardViewModel
的属性 class 并且 SomeDivToShowTheResult
是您页面中 div 的 ID您要加载来自局部视图的内容的位置。
发送复杂的对象?
如果需要,您可以在 js 中构建更复杂的对象。只要您的结构与视图模型匹配,模型绑定就会起作用 class
var model = { Name :"Shyju",
Location:"Detroit",
Interests : ["Code","Coffee","Whosebug"]
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json"
}).done(function (res) {
$("#SomeDivToShowTheResult").html(res);
});
要将上面的js模型转化为你的方法参数,你的视图模型应该是这样的。
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);
}
//C# class
public class DashBoardViewModel
{
public int Id { get; set;}
public decimal TotalSales { get; set;}
public string Url { get; set;}
public string MyDate{ get; set;}
}
//JavaScript file
//Create dashboard.js file
$(document).ready(function () {
// See the html on the View below
$('.dashboardUrl').on('click', function(){
var url = $(this).attr("href");
});
$("#inpDateCompleted").change(function () {
// Construct your view model to send to the controller
// Pass viewModel to ajax function
// Date
var myDate = $('.myDate').val();
// IF YOU USE @Html.EditorFor(), the myDate is as below
var myDate = $('#MyDate').val();
var viewModel = { Id : 1, TotalSales: 50, Url: url, MyDate: myDate };
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: '/Dashboard/IndexPartial',
data: viewModel ,
success: function (data, textStatus, jqXHR) {
//Do Stuff
$("#DailyInvoiceItems").html(data.Id);
},
error: function (jqXHR, textStatus, errorThrown) {
//Do Stuff or Nothing
}
});
});
});
//ASP.NET 5 MVC 6 Controller
public class DashboardController {
[HttpGet]
public IActionResult IndexPartial(DashBoardViewModel viewModel )
{
// Do stuff with my model
var model = new DashBoardViewModel { Id = 23 /* Some more results here*/ };
return Json(model);
}
}
// MVC View
// Include jQuerylibrary
// Include dashboard.js
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/dashboard.js"></script>
// If you want to capture your URL dynamically
<div>
<a class="dashboardUrl" href ="@Url.Action("IndexPartial","Dashboard")"> LinkText </a>
</div>
<div>
<input class="myDate" type="text"/>
//OR
@Html.EditorFor(model => model.MyDate)
</div>
正如其他答案中所建议的那样,将表单数据 "POST" 发送到控制器可能是最简单的方法。如果您需要传递整个 Model/Form,您可以使用 serialize()
轻松完成此操作,例如
$('#myform').on('submit', function(e){
e.preventDefault();
var formData = $(this).serialize();
$.post('/student/update', formData, function(response){
//Do something with response
});
});
因此您的控制器可以将视图模型作为参数,例如
[HttpPost]
public JsonResult Update(StudentViewModel studentViewModel)
{}
或者,如果您只想post一些特定的值,您可以这样做:
$('#myform').on('submit', function(e){
e.preventDefault();
var studentId = $(this).find('#Student_StudentId');
var isActive = $(this).find('#Student_IsActive');
$.post('/my/url', {studentId : studentId, isActive : isActive}, function(response){
//Do something with response
});
});
控制器如:
[HttpPost]
public JsonResult Update(int studentId, bool isActive)
{}
使用以下JS:
$(document).ready(function () {
$("#btnsubmit").click(function () {
$.ajax({
type: "POST",
url: '/Plan/PlanManage', //your action
data: $('#PlanForm').serialize(), //your form name.it takes all the values of model
dataType: 'json',
success: function (result) {
console.log(result);
}
})
return false;
});
});
以及控制器上的以下代码:
[HttpPost]
public string PlanManage(Plan objplan) //model plan
{
}
我正在尝试使用 JQuery/Ajax 将我的模型传递给控制器,但我不确定如何正确执行此操作。到目前为止,我已经尝试使用 Url.Action
,但模型是空白的。
注意:Whosebug 上的 none 个重复线程似乎使用 ASP.NET 5 MVC 6.
来解决查看:
$("#inpDateCompleted").change(function () {
var url = '@(Url.Action("IndexPartial", "DashBoard", Model, null))';
$("#DailyInvoiceItems").load(url);
});
控制器:
[HttpGet]
public PartialViewResult IndexPartial(DashBoardViewModel m)
{
// Do stuff with my model
return PartialView("_IndexPartial");
}
看起来您的 IndexPartial
操作方法有一个参数,它是一个复杂的对象。如果您传递大量数据(复杂对象),将您的操作方法转换为 HttpPost
操作方法并使用 jQuery post
到 [=41= 可能是个好主意] 数据到那个。 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);
});
假设 Name
和 Location
是您 DashboardViewModel
的属性 class 并且 SomeDivToShowTheResult
是您页面中 div 的 ID您要加载来自局部视图的内容的位置。
发送复杂的对象?
如果需要,您可以在 js 中构建更复杂的对象。只要您的结构与视图模型匹配,模型绑定就会起作用 class
var model = { Name :"Shyju",
Location:"Detroit",
Interests : ["Code","Coffee","Whosebug"]
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json"
}).done(function (res) {
$("#SomeDivToShowTheResult").html(res);
});
要将上面的js模型转化为你的方法参数,你的视图模型应该是这样的。
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);
}
//C# class
public class DashBoardViewModel
{
public int Id { get; set;}
public decimal TotalSales { get; set;}
public string Url { get; set;}
public string MyDate{ get; set;}
}
//JavaScript file
//Create dashboard.js file
$(document).ready(function () {
// See the html on the View below
$('.dashboardUrl').on('click', function(){
var url = $(this).attr("href");
});
$("#inpDateCompleted").change(function () {
// Construct your view model to send to the controller
// Pass viewModel to ajax function
// Date
var myDate = $('.myDate').val();
// IF YOU USE @Html.EditorFor(), the myDate is as below
var myDate = $('#MyDate').val();
var viewModel = { Id : 1, TotalSales: 50, Url: url, MyDate: myDate };
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: '/Dashboard/IndexPartial',
data: viewModel ,
success: function (data, textStatus, jqXHR) {
//Do Stuff
$("#DailyInvoiceItems").html(data.Id);
},
error: function (jqXHR, textStatus, errorThrown) {
//Do Stuff or Nothing
}
});
});
});
//ASP.NET 5 MVC 6 Controller
public class DashboardController {
[HttpGet]
public IActionResult IndexPartial(DashBoardViewModel viewModel )
{
// Do stuff with my model
var model = new DashBoardViewModel { Id = 23 /* Some more results here*/ };
return Json(model);
}
}
// MVC View
// Include jQuerylibrary
// Include dashboard.js
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/dashboard.js"></script>
// If you want to capture your URL dynamically
<div>
<a class="dashboardUrl" href ="@Url.Action("IndexPartial","Dashboard")"> LinkText </a>
</div>
<div>
<input class="myDate" type="text"/>
//OR
@Html.EditorFor(model => model.MyDate)
</div>
正如其他答案中所建议的那样,将表单数据 "POST" 发送到控制器可能是最简单的方法。如果您需要传递整个 Model/Form,您可以使用 serialize()
轻松完成此操作,例如
$('#myform').on('submit', function(e){
e.preventDefault();
var formData = $(this).serialize();
$.post('/student/update', formData, function(response){
//Do something with response
});
});
因此您的控制器可以将视图模型作为参数,例如
[HttpPost]
public JsonResult Update(StudentViewModel studentViewModel)
{}
或者,如果您只想post一些特定的值,您可以这样做:
$('#myform').on('submit', function(e){
e.preventDefault();
var studentId = $(this).find('#Student_StudentId');
var isActive = $(this).find('#Student_IsActive');
$.post('/my/url', {studentId : studentId, isActive : isActive}, function(response){
//Do something with response
});
});
控制器如:
[HttpPost]
public JsonResult Update(int studentId, bool isActive)
{}
使用以下JS:
$(document).ready(function () {
$("#btnsubmit").click(function () {
$.ajax({
type: "POST",
url: '/Plan/PlanManage', //your action
data: $('#PlanForm').serialize(), //your form name.it takes all the values of model
dataType: 'json',
success: function (result) {
console.log(result);
}
})
return false;
});
});
以及控制器上的以下代码:
[HttpPost]
public string PlanManage(Plan objplan) //model plan
{
}