![](/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.