Weird problem: 60-40 database update rate while creating records in ASP.NET MVC 3 with Razor using SQL Server 2008 R2
Guys I have a really weird thing going on in mvc3. Am using C# as the programming language and using SQL Server 2008 R2 as server and am using Linq-to-SQL.
When I am creating records things are being updated and now and then they don't get updated. I set breakpoints and checked and found nothing work in the code. But at times when doing breakpoint checks at times (not always) even though data is present in the page it (data) doesn't get passed to the UpdateModel(visitor)
method and then I get the exception which says
The model of type 'VisitorTrackingSystem.Models.Visitor' could not be update开发者_StackOverflowd.
I am totally confused. Is there a bug in the MVC3 code that causes this? And I have a total of 7 tables in this database and only one particular table has the problem.
[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 });
}
This exception could happen if the user tries to send some value which cannot be bound to the corresponding model property. For example the user enters "foo bar"
in a textbox which should be bound to an integer property. You could use the TryUpdateModel instead:
[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 });
}
or a bit easier:
[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 });
}
I found what is causing this weirdness. Problem is on user end. When the value in a particular entry doesn't match with the respective foreign key the exception occurs. None the less the validation provided by Darin Dimitrov is useful.
精彩评论