![](/img/trans.png)
[英]Creating Crystal Report in asp.net c# with SQL Server 2008 R2
[英]Weird problem: 60-40 database update rate while creating records in ASP.NET MVC 3 with Razor using SQL Server 2008 R2
伙计们,我在mvc3中发生了一件非常奇怪的事情。 我正在使用C#作为编程语言,并且正在使用SQL Server 2008 R2作为服务器,并且正在使用Linq-to-SQL。
当我创建记录时,事物正在更新,现在又不更新。 我设置了断点并检查,发现代码中没有任何工作。 但是有时有时(并非总是)执行断点检查,即使页面中存在数据,它(数据)也不会传递给UpdateModel(visitor)
方法,然后我得到了异常提示
无法更新“ VisitorTrackingSystem.Models.Visitor”类型的模型。
我很困惑。 MVC3代码中是否存在导致此错误的错误? 我在这个数据库中总共有7个表,只有一个特定的表有问题。
[HttpPost]
public ActionResult Create(FormCollection collection) //Creates a new record
{
Visitor visitor = new Visitor();
try
{
// TODO: Add insert logic here
UpdateModel(visitor);
visitorRepository.Add(visitor);
visitorRepository.Save();
}
catch(Exception e)
{
var exMsg = e.Message;
return View("Exception");
}
return RedirectToAction("Details", new { id = visitor.ID });
}
如果用户尝试发送一些无法绑定到相应模型属性的值,则可能发生此异常。 例如,用户在应绑定到整数属性的文本框中输入"foo bar"
。 您可以改用TryUpdateModel:
[HttpPost]
public ActionResult Create()
{
Visitor visitor = new Visitor();
if (!TryUpdateModel(visitor))
{
// There was a model error => redisplay the view so
// that the user can fix it
return View();
}
try
{
visitorRepository.Add(visitor);
visitorRepository.Save();
}
catch(Exception e)
{
var exMsg = e.Message;
return View("Exception");
}
return RedirectToAction("Details", new { id = visitor.ID });
}
还是容易一些:
[HttpPost]
public ActionResult Create(Visitor visitor)
{
if (!ModelState.IsValid)
{
// There was a model error => redisplay the view so
// that the user can fix it
return View();
}
// you don't really need those try/catch here
// simply leave the exception propagate and the
// HandleError global exception filter
// will render the ~/Shared/Error.cshtml view passing
// the exception details
visitorRepository.Add(visitor);
visitorRepository.Save();
return RedirectToAction("Details", new { id = visitor.ID });
}
我发现了造成这种奇怪现象的原因。 问题出在用户端。 当特定条目中的值与相应的外键不匹配时,将发生异常。 尽管如此,Darin Dimitrov提供的验证仍然有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.