在我看来,我有一个带有 foreach 循环的表,用于显示模型中的数据。
<table id="dt_table_tools" class="table table-striped table-condensed">
<thead>
<tr>
<th>@Html.DisplayNameFor(model => model.ItemOptions.First().Active)</th>
<th>@Html.DisplayNameFor(model => model.ItemOptions.First().ItemOptionCode)</th>
<th>@Html.DisplayNameFor(model => model.ItemOptions.First().Name)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (ItemDetailItemOptionViewModel ItemOption in Model.ItemOptions)
{
<tr>
<td>@Html.DisplayFor(model => ItemOption.Active)</td>
<td>@Html.DisplayFor(model => ItemOption.ItemOptionCode)</td>
<td>@Html.DisplayFor(model => ItemOption.Name)</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = ItemOption.ItemOptionId })
</td>
</tr>
}
</tbody>
</table>
然后我有一个模态表单,它允许我通过 ajax 回调添加新数据到服务器,然后它在表格末尾添加一行以显示新数据:
var handleSuccess = function (result) {
if (result.success) {
var $tr = $('<tr>').append(
$('<td>').text(result.Active),
$('<td>').text(result.ItemOptionCode),
$('<td>').text(result.Name),
$('<td>')
).appendTo('#dt_table_tools');
} else {
$('#itemOptionFormContainer').html(result);
}
};
这一切都正常,只是添加到表中的新行没有以相同的格式显示。例如,“Active”列显示“true”而不是复选框:
如何让 jquery 代码使用 @Html.DisplayFor(model => ItemOption.Active)
以便数据按预期显示?
最佳答案
您应该知道,DisplayFor
函数由服务器调用,而handleSuccess
函数将由客户端调用。
您想要做的是,让客户端调用 DisplayFor
函数。客户端(浏览器)不知道 DisplayFor
,它是 System.Web.Mvc.dll
中的一个 .NET 函数。
所以你应该做什么由“5te”解释。服务器应向您的 AJAX 调用返回 PartialViewResult
。为此,请创建一个 View 并将以下内容放入其中:
@model YourModelType
<tr>
<td>@Html.DisplayFor(m => m.ItemOption.Active)</td>
<td>@Html.DisplayFor(m => m.ItemOption.ItemOptionCode)</td>
<td>@Html.DisplayFor(m => m.ItemOption.Name)</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = ItemOption.ItemOptionId })
</td>
</tr>
在处理 AJAX 调用的 Action
中,执行以下操作:
ActionResult YourAjaxHandlingAction(...args...)
{
if(/*There is no error in your model*/)
{
YourModelType model = new YourModelType();
// initialize an instance of YourModelType
// using ...args...
model.ItemOption.Active = ...;
model.ItemOption.ItemOptionCode = ...;
model.ItemOption.Name = ...;
return PartialView("NewlyCreatedViewName", model);
}
else
{
// You can choose whatever http status code makes sense
// e.g 301, 400 etc..
return HttpStatusCodeResult(400, "An error occurred");
}
}
现在,在 Javascript 中,您应该像之前一样附加传入的 HTML。根据您进行 ajax 调用的方式,这部分会发生变化(AjaxHelper
或 jquery.ajax
?)。
编辑
我已经编辑了上面的代码,以包含发生错误时应该执行的操作。 当您进行 AJAX 调用时,您可以使用失败处理程序在屏幕上显示您想要的任何内容。
关于jquery - 在 jquery ajax 插入中使用 HTML.DisplayFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20920465/