我想在实体模型中编辑ASP MVC中的数据。但是,在发送表单时,我的控制器会收到空值(控制器中的错误)。 我不知道为什么会这样。我是MVC的新手。
System.NullReferenceException: 'Object reference not set to an instance of an
object.'
getmenu was null.
我不明白为什么它有空值。谁能详细说明?
模型
namespace Shop
{
using System;
using System.Collections.Generic;
public partial class menu
{
public int id { get; set; }
public string name { get; set; }
public string type { get; set; }
public Nullable<double> price { get; set; }
}
}
查看
@model Shop.menu
@{
ViewBag.Title = "edit";
}
<h2>edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>menu</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.id)
<div class="form-group">
@Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.type, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.type, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.type, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.price, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.price, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.price, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
控制器
namespace Shop.Controllers
{
public class HomeController : Controller
{
shopcontext db = new shopcontext();
public ActionResult edit()
{
return View();
}
[HttpPost]
public ActionResult edit(menu menu)
{
var getmenu = db.menus.Where(p => p.id == menu.id).FirstOrDefault();
getmenu.name = menu.name;
getmenu.type = menu.type;
getmenu.price = menu.price;
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
这些都是代码。请让我知道你的想法!
答案 0 :(得分:0)
替换
@using (Html.BeginForm())
通过
@using (Html.BeginForm("edit", "Home", FormMethod.Post))
2
[HttpGet]
public ActionResult edit()
{
var model= new Shop.menu();
return View(model);
}
3
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult edit(menu menu)
{
//........
}