Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 Add & Display Message through ModelState

I have a scenario like i need to display error message which is coming from DB on Edit [GET] request.

I know this can be done if request type is of [POST], but how can we do this in [GET] request.

Same Code:

    [HttpGet]
    public ActionResult Edit(Int64 ID)
      {
         tblSample1 model = GetData(ID);
         ViewData.ModelState.AddModelError(model.Username, "Invalid Username provided.");
         return View("~/Views/Sample1/_Edit.cshtml", model);
      }

[HttpPost]
public ActionResult Edit(tblSample1 model)
  {
     if (ModelState.IsValid)
        {
           ......
           ......
        }
  }

like image 373
Sham Avatar asked Dec 21 '22 02:12

Sham


1 Answers

This should still work. The first argument to AddModelError is the key. You're passing it the value of the property Username.. which won't work. What you want is to pass the property name as the key:

ModelState.AddModelError("Username", "Invalid Username provided.");
//                       ^^^^^^^^^^ Username property of model

Of course this must be coupled with a ValidationSummary or ValidationMessage in your view.

like image 163
Simon Whitehead Avatar answered Dec 22 '22 14:12

Simon Whitehead