我有一个页面,其中显示图像,ID,名称和地址。我添加了复选框和多个提交按钮以删除更新或添加新记录。
但是,当我单击任何提交按钮时,我得到了未处理的异常错误。 (例如,我选择了一个复选框,然后单击删除按钮,我的控件将从视图转到Mycontroller并进入删除开关案例。它正在删除记录,但是再次返回视图时,我得到了NullReferenceException。)>
查看:
@using (Html.BeginForm("MyAction", "MyController", FormMethod.Post))
{
@if (Model.Count> 0) // .NullReferenceException
{
@foreach (var MyDB in Model)
{
<div class="col-md-2">
<img src="@Url.Content(photos.photo_url)" style="width:100px; height:100px;" />
</div>
Html.LabelFor(model => MyDB.ID, new
{
@class = "control-label col-md-2"
})
<div class="col-md-2">
@Html.EditorFor(model => MyDB.ID)
@Html.ValidationMessageFor(model => MyDB.ID)
</div>
@Html.LabelFor(model => MyDB.name, new
{
@class = "control-label col-md-2"
})
<div class="col-md-2">
@Html.EditorFor(model => MyDB.name)
@Html.ValidationMessageFor(model => MyDB.name)
</div>
@Html.LabelFor(model => MyDB.address, new
{
@class = "control-label col-md-2"
})
<div class="col-md-2">
@Html.EditorFor(model => MyDB.address)
@Html.ValidationMessageFor(model => MyDB.address)
</div>
<div class="col-md-1">
input type="checkbox" class="checkboxes" value="@MyDB.id" name="id" />
</div>
}
}
}
<div class="col-md-offset-2 col-md-10">
<input type="submit" name="submitButton" value="UPDATE" />
<input type="submit" name="submitButton" value="ADD" />
<input type="submit" name="submitButton" value="DELETE" />
</div>
控制器:
public ActionResult MyController(IEnumerable<int> id, string submitButton)
{
switch (submitButton)
{
case "DELETE":
foreach (var item in id)
{
var delete = _db.MyDB.FirstOrDefault(s => s.id == item);
if (delete != null)
{
_db.MyDB.Remove(delete);
}
}
break;
case "ADD":
if (!ModelState.IsValid)
{
return RedirectToAction("ADDRecordPage", new
{
id
});
}
if (id == null)
{
return RedirectToAction("ADDRecordPage", new
{
id
});
}
break;
case "UPDATE" :
ViewBag.Message = "UPDATE";
break;
}
_db.SaveChanges();
ViewBag.Message = "Saved";
return View();
}
答案 0 :(得分:0)
我发现自己犯了什么错误。在控制器内部,我添加了return View();它返回null。因此更改为返回RedirectToAction(“ MyAction”,new {id});而不是返回View();