我正在使用Ajax帖子提交一些信息,该帖子应该刷新部分视图。信息被发送到数据库但是在返回局部视图时,Fees.Feetype数据无法呈现为null。
在手动刷新时,Fees.FeeType呈现没有问题。
如何在ajax发布后将FeeType包含在局部视图中?
模型
public class Members
{
public virtual ICollection<Fees> Fees { get; set; }
}
public class Fees
{
public int FeeTypesId { get; set; }
public virtual FeeTypes FeeType { get; set; }
public virtual Members Members { get; set; }
}
public class FeeTypes
{
public int Id { get; set; }
public string FeeTypeName { get; set; }
}
Ajax Post
var token = $('[name=__RequestVerificationToken]').val();
var postData = {
__RequestVerificationToken: token,
FeeOccurence: feeOccField.val(),
FeeAmount: amountField.val(),
FeeStatus: statusField.val(),
FeeTypesId: typeField.val(),
FeeDate: dateField.val(),
MemberNo: memberNo
};
$.ajax({
url: '/Members/AddFees',
type: 'POST',
data: postData,
success: function (members) {
alert(result);
$("#details").html(members);
},
error: function (result) {
alert(result);
},
traditional: true
控制器
public ActionResult AddFees (Fees fees)
{
if (ModelState.IsValid)
{
db.Fees.Add(fees);
db.SaveChanges();
Members members = new Members();
members = db.Members.Find(fees.MemberNo);
return PartialView("~/Views/Members/_MemberDetails.cshtml", members);
}
}
浏览
@model AccPortal.Models.Members
<div class="col-md-7 md-fees" id ="details">
@Html.Partial("_MemberDetails", Model)
</div>
//This is the partial view.
@model AccPortal.Models.Members
@foreach (var item in Model.Fees)
{
//The error happens on this line but all other Fees properties are rendered without issue.
<td class="md-fee-value"data-type="status">@item.FeeType.FeeTypeName</td>
}
答案 0 :(得分:1)
这些是您需要在代码中更改的内容,
首先,使用Action方法返回一个带有模型的局部视图,如下所示,
return PartialView("_MemberDetails", members);
Datatype
应该是你的ajax方法中的html。所以在ajax方法中添加这个波纹管线。您可以在此行data: postData,
dataType: "html",
现在在你的ajax成功方法中,改变这样,
success: function (members) {
//alert(result); what is result here, that you have written
$("#details").html(''); //first make it blank then render
$("#details").html(members);
},
在局部视图中,您需要在渲染值
之前检查FeeType是否存在@model AccPortal.Models.Members
@foreach (var item in Model.Fees)
{
if(item.FeeType != null)
<td class="md-fee-value"data-type="status">@item.FeeType.FeeTypeName</td>
else
<td class="md-fee-value"data-type="status"></td> //You can write NA here
}
答案 1 :(得分:1)
null类型的问题最后是延迟加载。
我保存更改后必须重新查询数据库,并包含Fees.FeeTypes以返回正确填充的模型。
members = db.Members.Find(fees.MemberNo);
members.Fees = db.Fees.Include(x => x.FeeType).Where(x => x.Members.MemberNo.Equals(x.MemberNo)).ToList();
答案 2 :(得分:0)
您需要在填充列表前检查null
值,以避免null exception
@model AccPortal.Models.Members
@foreach (var item in Model.Fees)
{
if(item.FeeType != null)
<td class="md-fee-value"data-type="status">@item.FeeType.FeeTypeName</td>
}
因为某些数据可能会丢失而导致问题,所以在if
条件下,它只会填充not null