0

Please help me to show Error message in the view. My code is given below -

This is my View Model:

public class DepartmentViewModel
{
    //public Department Department { get; set; }
    public string DepartmentId { get; set; }
    [Required]
    public string DepartmentName { get; set; }
    public string ManagerMemberId { get; set; }
    public bool IsActive { get; set; }
    public List<Member> Managers { get; set; } 
}

This is Controller:

public class DepartmentController : Controller
{
    //
    // GET: /Department/

    public ActionResult Index()
    {
        var adminUserId = (string)Session["UserId"];
        var memberId = (string)Session["MemberId"];

        List<Department> departments = null;

        if (!string.IsNullOrEmpty(adminUserId))
        {
            departments = new DepartmentManager().GetDepartments(false);
        }
        else if (!string.IsNullOrEmpty(memberId))
        {
            var companyId = (int)Session["CompanyId"];
            departments = new DepartmentManager().GetDepartments(false, companyId);
        }

        //var managers = new MemberManager().GetMembersOfManagerCategory(true, );

        return View("DepartmentList", departments);
    }


    public ActionResult Delete(string departmentId)
    {
        try
        {
            new DepartmentManager().DeleteDepartment(departmentId);
        }
        catch (System.Exception exception)
        {
            ModelState.AddModelError("Error", "Unable to delete department. Try again,      and if the problem persists see your system administrator.");
            //return RedirectToAction("Index", "Department");
        }

        return RedirectToAction("Index", "Department");
    }
}

This is View:

@model IEnumerable<PDCA.Core.EntityClasses.Department>
@{
    ViewBag.Title = "Department List";
    Layout = "~/Views/Shared/_Layout.cshtml";
 }
<div class="container">
@using (Html.BeginForm())
{
    <form class="form-horizontal">
    <fieldset>
        <legend>List of Departments:</legend>
        <table border="1" cellspacing="1">
            <tr>
                <th>
                    Id
                </th>
                <th>
                    Name
                </th>
                <th>
                    Company
                </th>
                <th>
                    Manager
                </th>
                <th>
                    IsActive
                </th>
                <th>
                </th>
            </tr>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.DepartmentId)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.DepartmentName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Company.CompanyName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Manager.MemberName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.IsActive)
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Edit", new { item.DepartmentId }) |
                        @Html.ActionLink("Delete", "Delete", new { item.DepartmentId })
                    </td>
                </tr>
            }
        </table>
        <p></p>
        <p>
            @Html.ActionLink("Create New", "Create")
        </p>
        <p></p>
        <p>
            @Html.ValidationMessage("Error");
        </p>
    </fieldset>
    </form>
}

In the view I put @Html.ValidationMessage("Error") but the error message is not shown there.

Mayeed
  • 691
  • 1
  • 7
  • 19

3 Answers3

1

Firstly you have a duplicate form

@using (Html.BeginForm())
{
    <form class="form-horizontal">

@Html.BeginForm takes care of the form tags for you.

Secondly, try adding @Html.ValidationSummary like so

@using (Html.BeginForm())
{
    @Html.ValidationSummary()
    <fieldset>

Thirdly, you need to reference the correct script files. Typically this would be done in a layout page but that is up to you.

Add references to

jquery
jquery.validate.js
jquery.validate.unobtrusive.j

CDNs can be found here

Assuming you don't enter a DepartmentName, press submit and you should see the error message.

Bear in mind that the model for your page has to be DepartmentViewModel. In your example above it isn't.

glosrob
  • 6,631
  • 4
  • 43
  • 73
1

You are redirecting, so modelstate is gone. You can save it through tempdata, but I wouldn't go that way (How do I maintain ModelState errors when using RedirectToAction?). You can show error with special field and some notification message (eg. toastr), or simply stay on the same view and then modelstate errors will show.

public ActionResult Delete(string departmentId)
    {
        try
        {
            new DepartmentManager().DeleteDepartment(departmentId);
        }
        catch (System.Exception exception)
        {
            ModelState.AddModelError("Error", "Unable to delete department. Try again,      and if the problem persists see your system administrator.");
            //return RedirectToAction("Index", "Department");
YOU SHOULD ADD MESSAGE TO VIEWDATA HERE, OR RETURN SAME VIEW(make delete POST action also)

        }
    return RedirectToAction("Index", "Department");
}
Community
  • 1
  • 1
MiBu
  • 869
  • 8
  • 17
  • Can you elaborate a little more please. I did not get you. – Mayeed Mar 14 '13 at 15:24
  • Go to the link in my answer; ModelState is not persisted on redirect. You are caching the error, putting it in modelstate, but redirecting after -> you need to persist modelstate(solutions in link), but I would consider refactoring it. P.S. I'd make a few changes to your code(make delete action Post, get elmah for error logging- with try catch it will be hard to debug...) – MiBu Mar 15 '13 at 12:39
0

try adding the validation summary as also suggested by @glosrob like

@using (Html.BeginForm()) 
{
   @Html.ValidationSummary()
...

also use ValidationMessageFor like

<td>
     @Html.DisplayFor(modelItem => item.DepartmentName)
     @Html.ValidationMessageFor(v=>v.DepartmentName)
 </td>
Rafay
  • 30,950
  • 5
  • 68
  • 101