[RESOLVED]ModelState.AddModelError doesn't show error

<div>Controller action:</div> <div>

TempData["CustomError"] = "Duplicate names exist";

if (matchingOnes != null && matchingOnes.Count > 0)
{
    this.ModelState.AddModelError("Name", TempData["CustomError"].ToString());
    var ValueProviderResult = ModelState.Values;
    return true;
}
else
{
    return false;
}

View Page:

@using (Ajax.BeginForm(MVC.Customer.Create(), new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "CreateSection", OnSuccess = "HandleSuccess" }, new { id = "CustomerPageForm" }))
{
@Html.ValidationSummary(true)
<fieldset class="form-horizontal">

<div class="control-group">
<label class="control-label">Country Traffic</label>
<div class="controls">
@Html.DropDownListFor(model => model.Country, ViewBag.CountryList as SelectList, "Select All", new { @Multiple = "", @style = "min-width: 220px;", placeholder = "Select…." })
@Html.HiddenFor(model => model.Country1.ShortCode1)
@Html.ValidationMessageFor(model => model.Country)
</div>
</div>

<div class="control-group">
@Html.LabelFor(model => model.Name, null, new { @class = "control-label" })
<div class="controls">

@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)

</div>
</div>

two questions

1) where is CreateSection defined?

2) does the Create Action view return a ValidationSummary?

this is my create view page – Create button:

Q1) I do not know what is your mean?

Q2)<div class="control-group">
<div class="controls">
<input id="btnSupplier" type="submit" value="Create" onclick="getDupplicating();" class="btn btn-success" />
@Html.ActionLink("Back to List", "Index")
</div>
</div>

your ajax form will take the response html and replaces the content under the dom element CreateSection. as long as the html contain a validation summary, it will display the error.

you posted code does not include the CreateSection, and the controller code does not show it returns a view, and you don’t show the view code. so there are several places for a coding error. 

hmsarab

if (matchingOnes != null && matchingOnes.Count > 0)
{
    this.ModelState.AddModelError("Name", TempData["CustomError"].ToString());
    var ValueProviderResult = ModelState.Values;
    return true;
}
else
{
    return false;
}

This method should return result of type viewresuly or actionresult

And you should return the view

this.ModelState.AddModelError("Name", TempData["CustomError"].ToString());

by the above statement, view engine renders  the validationsummery with the error

the

Leave a Reply