我正在学习 ASP.NET MVC。我正在关注有关的基本教程之一asp.net http://www.asp.net/mvc/whatisaspmvc/。由于我并不总是严格遵循教程,因此我决定使用 GUID 作为标识列而不是整数。一切都工作正常,直到我通过 MVC 应用程序向数据库添加新记录为止。当我添加新记录时,它插入了一个空白 GUID,而不是生成的 GUID。这是处理插入的隐藏代码段:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "id")]Movie movieToCreate)
{
try
{
_entities.AddToMovieSet(movieToCreate);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
The [Bind(Exclude = "id")]
行“忽略”ID 列,因为它是自动生成的。在本教程中,ID 是自动递增的,但我认为这是因为它是一个整数。我尝试在这个方法中添加一行:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "id")]Movie movieToCreate)
{
try
{
movieToCreate.id = Guid.NewGuid();
_entities.AddToMovieSet(movieToCreate);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
但 id 仍然是一个空的 GUID。任何人都可以向我提供一些关于为什么会出现这种情况以及如何解决它的信息吗?
您可以使用自定义 ModelBinder。我了解了那些here https://stackoverflow.com/questions/1173678/mvc-updatemodel-when-the-names-dont-match-up.
public class MyClassBinder : DefaultModelBinder {
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) {
var model = (Movie)base.CreateModel(controllerContext, bindingContext, modelType);
model.id = Guid.NewGuid();
return model;
}
}
你的动作控制器将是:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyAction(Movie movieToCreate) {
// movie should have a new guid in the id
_entities.AddToMovieSet(movieToCreate);
_entities.SaveChanges();
}
您需要在 Global.asax 中注册活页夹:
protected void Application_Start() {
RegisterRoutes(RouteTable.Routes);
ModelBinders.Binders.Add(typeof(Movie), new MyClassBinder());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)