Dave
Dave

Reputation: 263

Validation Message is not Displayed on View

This is not a repeated question am posting this question after trying all solutions.

I want to perform CRUD on a single View so I got this article

CRUD using SIngle View

It works fine but when I keep the text box empty then the Model is Valid returns false which is correct,after debugging it shows Name field is required but I cant see the error on the View.

Even @Html.ValidationSummary(true) is present in Begin Form and @Html.ValidationMessageFor(model => model.Name)

So keeping the code short have used only one field

Model

public partial class tblClient
{   
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }
}

A class which handle multiple button

public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
            return true;

        var request = controllerContext.RequestContext.HttpContext.Request;
        return request[methodInfo.Name] != null;
    }
}  

Controller

public class EmpController : Controller
{

    SampleEntities1 db = new SampleEntities1();  
    //
    // GET: /Emp/
    public ActionResult Index(int? id)  
    {  
        ViewBag.Operation = id;  
        ViewBag.Name = db.tblClients.ToList();  
        tblClient objEmp = db.tblClients.Find(id);  
        return View(objEmp);  
    }  

    [HttpPost]  
    [HttpParamAction]  
    [ValidateAntiForgeryToken]  
    public ActionResult Create(tblClient objEmp)   
    {  
        if (ModelState.IsValid)  
        {  
            db.tblClients.Add(objEmp);  
            db.SaveChanges();  
        }  
        return RedirectToAction("Index");  
    }  

    [HttpPost]  
    [HttpParamAction]  
    [ValidateAntiForgeryToken]  
    public ActionResult Update(tblClient objEmp)  
    {  
        if (ModelState.IsValid)  
        {  
            db.Entry(objEmp).State = EntityState.Modified;  
            db.SaveChanges();  
        }  
        return RedirectToAction("Index", new { id = 0 });  
    }  

    public ActionResult Delete(int id)  
    {  
        tblClient objEmp = db.tblClients.Find(id);  
        db.tblClients.Remove(objEmp);  
        db.SaveChanges();  
        return RedirectToAction("Index", new { id = 0 });  
    }  
}  

View

@using (Html.BeginForm())
  {

<fieldset>
    <legend><b>Emp Details</b></legend>
    <table border="1" cellpadding="10">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>

            <th>
                Action
            </th>
        </tr>

        @foreach (var item in (IEnumerable<SingleVIewCrud.Models.tblClient>)ViewBag.Name)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.ActionLink("Edit", "Index", new { id = item.Id }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.Id })
                </td>
            </tr>
        }

    </table>
</fieldset>

        @Html.AntiForgeryToken()
        <div class="form-horizontal">
            @Html.ValidationSummary(true)

            <fieldset>
                <legend> <b>Entry Screen</b></legend>

                <div class="form-group">
                    @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Name)
                        @Html.ValidationMessageFor(model => model.Name)
                    </div>
                </div>

                <div class="form-group">
                    <p>
                        <input type="submit" value="Create" name="Create"
                               style=@((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:none" : "display:block") />
                        <input type="submit" value="Update" name="Update"
                               style=@((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:block" : "display:none") />
                    </p>
                </div>
            </fieldset>
        </div>
}

What is wrong that the validation error message is not displayed.

Upvotes: 0

Views: 235

Answers (1)

user3559349
user3559349

Reputation:

In both your Create() and Edit() POST methods, if ModelState is invalid, you just redirecting to the Index() view. You need to return the existing view -

if (!ModelState.IsValid()
{
    return View(objEmp);
}
// save and redirect
db.tblClients.Add(objEmp);  
db.SaveChanges();  
return RedirectToAction("Index");  

Side note: If you include the jquery.validate.js and jquery.validate.unobtrusive.js scripts, then you will also get client side validation and the POST methods will not even be hit - the validation messages will be displayed and the submit will be cancelled

Upvotes: 1

Related Questions