开发者

How to validate a dropdownlist populated from the database in ASP.NET MVC3?

开发者 https://www.devze.com 2023-02-03 18:24 出处:网络
I have 2 tables, Person and Nationality. Person has an FK to the Nationality table via NationalityID. In my Create Person form, I\'ve got a dropdown that\'s populated with NationalityID and Nationalit

I have 2 tables, Person and Nationality. Person has an FK to the Nationality table via NationalityID. In my Create Person form, I've got a dropdown that's populated with NationalityID and NationalityDescription. What's the best way to validate this dropdown to deal with people using developer toolbars etc to change the posted value to an invalid NationalityID? I've been looking at using Syste开发者_JAVA技巧m.DataAnnotations.AssociationAttribute in a viewmodel but I'm not sure if this is quite what I need.


This kind of validation should be performed by the business layer. For example:

[HttpPost]
public ActionResult Update(int nationalityId, int personId)
{
    string error;
    if (!Repository.TryUpdatePersonNationality(personId, nationalityId, out error))
    {
        // The business layer failed to perform the update 
        // due to FK constraint violation => add the error to model state
        ModelState.AddModelError(nationalityId, error);
        // redisplay the form so that the user can fix the error
        return View();
    }
    return RedirectToction("Success");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号