[英]Jquery $.ajax and load function cannot pass parameters to MVC controller to get partial view into modal dialog
Good time of the day, stack overflow community.一天中的好时光,堆栈溢出社区。 I was building my first application with jquery ajax calls, but I'm having troubles with getting customer information, passed from controller action method as partial view to show it in a modal dialog.我正在使用 jquery ajax 调用构建我的第一个应用程序,但是我在获取客户信息时遇到了麻烦,从控制器操作方法作为部分视图传递以在模式对话框中显示它。
When I use .load function it works as expected, but I cant pass any parameters to my controller action method.当我使用 .load 函数时,它按预期工作,但我无法将任何参数传递给我的控制器操作方法。 Then I tried to use $.ajax, but still no luck.然后我尝试使用 $.ajax,但仍然没有运气。
Let me post my code so you will have better idea of my problem.让我发布我的代码,以便您更好地了解我的问题。
My Main view我的主要观点
@model IEnumerable<App.AppService.Customer>
@{
ViewBag.Title = "GetCustomers";
}
<script type="text/javascript">
$(document).ready(function() {
var customerID = 0;
$("input[type=button]").click(function() {
customerID = this.id;
debugger;
$("#dialogDiv").dialog("open");
});
$(function() {
$('#dialogDiv').dialog({
autoOpen: false,
width: 400,
resizable: false,
title: 'Update customer information',
modal: true,
open: function() {
$.ajax({
url: '@Url.Action("GetCustomer", "Customer")',
contentType: 'application/json; charset=utf-8',
method: "get",
data: JSON.stringify({ customerId : customerID }),
dataType: 'html'
});
},
buttons: {
"Close": function() {
$(this).dialog("close");
}
}
});
});
});
</script>
<h2>GetCustomers</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<div class="row">
<div class="col-md-offset-1 col-md-10">
<table class="table table-condensed table-striped">
<tr>
<th class="text-center">
@Html.DisplayNameFor(model => model.CustomerName)
</th>
<th class="text-center">
@Html.DisplayNameFor(model => model.Company)
</th>
<th class="text-center">
@Html.DisplayNameFor(model => model.Email)
</th>
<th class="text-center">
@Html.DisplayNameFor(model => model.PhoneNumber)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr id="@item.CustomerID">
<td>
@Html.DisplayFor(modelItem => item.CustomerName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Company)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.DisplayFor(modelItem => item.PhoneNumber)
</td>
<td>
<input type="button" value="edit" id="@item.CustomerID" /> |
@Html.ActionLink("Delete", "Delete", new { id = item.CustomerID })
</td>
</tr>
}
</table>
</div>
</div>
<div id="dialogDiv" title="Edit customer">
<h3>Please wait ...</h3>
</div>
In this view I retrieve all the customers and when edit button is clicked I want to call controller method and retrieve customer by his id in modal dialog.在这个视图中,我检索所有客户,当单击编辑按钮时,我想调用控制器方法并在模式对话框中通过他的 id 检索客户。
Below is my controller ActionMethod:下面是我的控制器 ActionMethod:
[HttpGet]
public ActionResult GetCustomer(int customerId)
{
Customer customer = repository.GetCustomerById(customerId);
return PartialView("_GetCustomerPartial", customer);
}
[HttpPost]
public ActionResult GetCustomer(Customer customer)
{
if (repository.UpdateCustomer(customer))
{
return RedirectToAction("GetCustomers");
}
return HttpNotFound();
}
And my Partial View:还有我的部分观点:
@model App.AppService.Customer
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Customer</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Company)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Company)
@Html.ValidationMessageFor(model => model.Company)
</div>
@Html.HiddenFor(model => model.CustomerID)
<div class="editor-label">
@Html.LabelFor(model => model.CustomerName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CustomerName)
@Html.ValidationMessageFor(model => model.CustomerName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.PhoneNumber)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.PhoneNumber)
@Html.ValidationMessageFor(model => model.PhoneNumber)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
With this code I'm getting Null reference error.使用此代码,我收到 Null 引用错误。 I believe it is because parameters are not passed to action method.我相信这是因为参数没有传递给 action 方法。
If I use just a load function without any parameters (just for testing), it works perfectly and returns customer object as a partial view to my modal dialog.如果我只使用一个没有任何参数的加载函数(仅用于测试),它可以完美地工作并将客户对象作为局部视图返回到我的模态对话框。
Working code:工作代码:
$(document).ready(function () {
$("input[type=button]").click(function () {
var customerId = this.id;
debugger;
$("#dialogDiv").dialog("open");
});
$(function () {
$('#dialogDiv').dialog({
autoOpen: false,
width: 400,
resizable: false,
title: 'Update customer information',
modal: true,
open: function () {
debugger;
$(this).load("@Url.Action("GetCustomer")");
},
buttons: {
"Close": function() {
$(this).dialog("close");
}
}
});
});
});
With changes in controller action.随着控制器动作的变化。
[HttpGet]
public ActionResult GetCustomer()
{
Customer customer = repository.GetCustomerById(any int id);
return PartialView("_GetCustomerPartial", customer);
}
I want to achieve same working functionality, but with parameters I can pass to controller action method.我想实现相同的工作功能,但可以通过参数传递给控制器操作方法。
I went through this post, but unfortunately didn't understand the solution people provided in comments.我浏览了这篇文章,但不幸的是没有理解人们在评论中提供的解决方案。
Thank you in advance!先感谢您!
After continuously working on this issue I finally got it working.在不断研究这个问题之后,我终于让它工作了。 Below is the solution:下面是解决方案:
$("input[type=button]").click(function () {
var customerId = this.id;
$.ajax({
url: '@Url.Action("GetCustomer","Customer")',
contentType: 'application/json; charset=utf-8',
method: "get",
data: ({ customerId: customerId }),
dataType: 'html',
success: function (result) {
$("#dialogDiv").dialog("open").html(result);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$("#output").html(msg);
$("#output").css("visibility", "visible");
}
});
});
$(function () {
$('#dialogDiv').dialog({
autoOpen: false,
width: 400,
resizable: false,
title: 'Update customer information',
modal: true,
buttons: {
"Close": function() {
$(this).dialog("close");
}
}
});
});
Main points to mention here is that I was using $.ajax call in the wrong place, and removing JSON.stringify
helped my to avoid null reference exception.这里要提到的要点是我在错误的地方使用了 $.ajax 调用,删除JSON.stringify
帮助我避免了空引用异常。 As the return type from the action method was html and I just filled my dialog div with that html and everything worked like a charm.由于 action 方法的返回类型是 html,我只是用那个 html 填充了我的对话框 div,一切都像魅力一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.