我正在尝试使用asp.net mvc 4
& EF6
我希望一次更新多行。到目前为止一切正常,但是当我忽略视图中也会更新的字段时,我尝试更新时出现NullReferenceException
错误。这是我的代码,
控制器
[HttpPost]
public ActionResult DueCheck(FlatModel DueLists)
{
if (Session["username"] != null)
{
if (ModelState.IsValid)
{
foreach (var BillId in DueLists.BillCollection)
{
var dbRentSchedule = db.BillChecks.Where(p => p.billid == BillId.billid).FirstOrDefault();
if (dbRentSchedule != null)
{
dbRentSchedule.isRented = BillId.isRented;
if (BillId.isRented == "Y")
{
dbRentSchedule.isFull = "Y";
dbRentSchedule.due = 0;
}
}
else
{
return RedirectToAction("DueError");
}
}
db.SaveChanges();
return RedirectToAction("DueCheck");
}
else
{
return RedirectToAction("DueError");
}
}
else
{
return RedirectToAction("AdminLogin");
}
}
查看
@using (Html.BeginForm("DueCheck", "Home"))
{
@Html.ValidationSummary(true)
@for (int i = 0; i < Model.BillCollection.Count; i++ )
{
if(Model.BillCollection[i].fullname != "N/A" && Model.BillCollection[i].isFull != "Y") //If I remove the second condition then it works but will also show the records which is not needed.
{
<tr>
<td>@Html.DisplayFor(m => m.BillCollection[i].name)</td>
<td>@Html.HiddenFor(m => m.BillCollection[i].billid)@Html.DisplayFor(m => m.BillCollection[i].due)</td>
<td><div class="isFull btn btn-info">Approve</div>@Html.HiddenFor(m => m.BillCollection[i].isRented, new { @class = "assignFull" })</td>
</tr>
}
}
<input type="submit" class="btn btn-success" value="Update" />
}
如果我从视图中删除条件Model.BillCollection[i].isFull != "Y"
,那么它可以正常工作,但它也会显示不必要的记录,这使得我的系统毫无意义。如何从服务器端而不是客户端忽略那些记录?非常需要这个帮助。 TNX。
更新
BillCheck模型(EF6生成)
public partial class BillCheck
{
public string name { get; set; }
public string isRented { get; set; }
public string isFull { get; set; }
public int due { get; set; }
}
FlatManagement Model
public class FlatManagement
{
public List<BillPayCheck> BillCollection { get; set; }
}
答案 0 :(得分:0)
在填充BillCollection对象的linq中添加这两个条件
Model.BillCollection[i].fullname != "N/A" && Model.BillCollection[i].isFull != "Y"
你的linq应该像
db.BillCollection.Where(p => !p.fullname.equals("N/A") && !p.isFull.equals("Y"))