52

I have the following view,, which create 10 ajax.beginform ,, But the problem that i am facing is that incase an error occurs during the creation of the object then the ModelState.AddModelError will not be shown on the view although i have set the @Html.ValidationSummary(true) The view looks as follow

@model Medical.Models.VisitLabResult

@for (int item = 0; item < 10; item++)
{
    <tr id = @item>
    @using (Ajax.BeginForm("CreateAll", "VisitLabResult", new AjaxOptions
    {
        HttpMethod = "Post",
        UpdateTargetId = item.ToString() + "td",
        InsertionMode = InsertionMode.Replace,
        LoadingElementId = "progress2",
        OnSuccess = string.Format(
            "disableform({0})",
            Json.Encode(item)),
    }))
    {  
        @Html.ValidationSummary(true)

        @Html.AntiForgeryToken()
        <td>
            @Html.DropDownList("LabTestID", String.Empty)
            @Html.ValidationMessageFor(model => model.LabTestID)
        </td>
        <td>
            @Html.EditorFor(model => model.Result)
            @Html.ValidationMessageFor(model => model.Result)
        </td>

        <td>
            @Html.EditorFor(model => model.DateTaken)
            @Html.ValidationMessageFor(model => model.DateTaken)
        </td>

        <td>
            @Html.EditorFor(model => model.Comment)
            @Html.ValidationMessageFor(model => model.Comment)
        </td>

        <td>
            <input type="submit" value="Create" />
        </td>

        <td id = @(item.ToString() + "td")>
        </td>
    }
    </tr>
    }
</table>

And my action method which defines the ModelState.AddModelError looks as follow:-

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateAll(VisitLabResult vlr, int visitid = 28)
{
    try
    {
        if (ModelState.IsValid)
        {
            var v = repository.GetVisit(visitid);
            if (!(v.EligableToStart(User.Identity.Name))){ 
                return View("NotFound"); 
            }
            vlr.VisitID = visitid;
            repository.AddVisitLabResult(vlr);
            repository.Save();

            return Content("Addedd Succsfully");
        }
    }
    catch (DbUpdateException)
    {
        JsonRequestBehavior.AllowGet);
        ModelState.AddModelError(string.Empty, "The Same test Type might have been already created,, go back to the Visit page to see the avilalbe Lab Tests");
    }
}

So how i can show the ModelState.AddModelError on my view.

Ciarán Bruen
  • 5,221
  • 13
  • 59
  • 69
John John
  • 1
  • 72
  • 238
  • 501

3 Answers3

74


I would urge you to change your try{ } catch(){ }

And first check if there exists a visit for the given id and if so simply returns the model with the added model error

    if (visitExists)
    {
         ModelState.AddModelError("CustomError", "The Same test Type might have been already created,, go back to the Visit page to see the avilalbe Lab Tests");
         return View(vlr);    
    }
    //Other code here

Change your AddModelError To

ModelState.AddModelError("CustomError", "The Same test Type might have been already created,, go back to the Visit page to see the avilalbe Lab Tests");

And in your view simply add a

@Html.ValidationMessage("CustomError")

Then when you return your model the error will be shown where you have placed the @Html.ValidationMessage ...

Richard Ev
  • 52,939
  • 59
  • 191
  • 278
Syneryx
  • 1,278
  • 11
  • 18
  • 1
    How would you handle the html wrapping the error message? You only want the HTML (bootstrap alert for example) to show when there is an error. – J86 Jan 29 '17 at 14:23
10

@Html.ValidationSummary(true) shows only the error message about model's propertys, if you want to show also the added message, added with

ModelState.AddModelError(
    "CustomError", 
    "The Same test Type might have been already created, go back to the Visit page to see the avilalbe Lab Tests"); 

you need to set @Html.ValidationSummary(false) If you need to display the validation's message near your input fields you need to set @Html.ValidationSummary(true) and to follow the steps suggested by Syneryx

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
5

You can use from ViewData dictionary in View to access ModelState data.

For example:

in Action:

ModelState.AddModelError("CustomError", "Error 1");
ModelState.AddModelError("CustomError", "Error 2");

and to get "Error 1" message:

ViewData.ModelState["CustomError"].Errors[0].ErrorMessage
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Sayed Abolfazl Fatemi
  • 3,678
  • 3
  • 36
  • 48