C# 如何在asp.net mvc3中显示错误消息

C# 如何在asp.net mvc3中显示错误消息,c#,asp.net,asp.net-mvc-3,C#,Asp.net,Asp.net Mvc 3,请帮助我在视图中显示错误消息。我的代码如下: 这是我的视图模型: public class DepartmentViewModel { //public Department Department { get; set; } public string DepartmentId { get; set; } [Required] public string DepartmentName { get; set; } public string ManagerM

请帮助我在视图中显示错误消息。我的代码如下:

这是我的视图模型:

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; } 
}
公共类部门视图模型
{
//公共部门部门{get;set;}
公共字符串DepartmentId{get;set;}
[必需]
公共字符串DepartmentName{get;set;}
公共字符串ManagerMemberId{get;set;}
公共bool IsActive{get;set;}
公共列表管理器{get;set;}
}
这是控制器:

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");
    }
}
公共类部门控制器:控制器
{
//
//获得/部门/
公共行动结果索引()
{
var adminUserId=(字符串)会话[“UserId”];
var memberId=(字符串)会话[“memberId”];
列出部门=空;
如果(!string.IsNullOrEmpty(adminUserId))
{
部门=新部门经理().GetDepartments(false);
}
如果(!string.IsNullOrEmpty(memberId))为else
{
var companyId=(int)会话[“companyId”];
部门=新部门经理().GetDepartments(false,companyId);
}
//var managers=new MemberManager();
返回视图(“部门列表”,部门);
}
公共操作结果删除(字符串部门ID)
{
尝试
{
新部门经理().DeleteDepartment(部门ID);
}
捕获(System.Exception异常)
{
AddModelError(“错误”,“无法删除部门。请重试,如果问题仍然存在,请与系统管理员联系。”);
//返回操作(“索引”、“部门”);
}
返回操作(“索引”、“部门”);
}
}
这是一种观点:

@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>
}
@model IEnumerable
@{
ViewBag.Title=“部门列表”;
Layout=“~/Views/Shared/_Layout.cshtml”;
}
@使用(Html.BeginForm())
{
部门名单:
身份证件
名称
单位
经理
活跃的
@foreach(模型中的var项目)
{
@DisplayFor(modelItem=>item.DepartmentId)
@DisplayFor(modelItem=>item.DepartmentName)
@DisplayFor(modelItem=>item.Company.CompanyName)
@DisplayFor(modelItem=>item.Manager.MemberName)
@DisplayFor(modelItem=>item.IsActive)
@ActionLink(“编辑”,“编辑”,新的{item.DepartmentId})|
@ActionLink(“删除”,“删除”,新的{item.DepartmentId})
}

@ActionLink(“新建”、“创建”)

@验证消息(“错误”);

}


在视图中,我放置了@Html.ValidationMessage(“错误”),但错误消息没有显示在那里。

首先,您有一个重复的表单

@using (Html.BeginForm())
{
    <form class="form-horizontal">
第三,您需要引用正确的脚本文件。通常,这将在布局页面中完成,但这取决于您

添加对的引用

jquery
jquery.validate.js
jquery.validate.unobtrusive.j
可以找到CDN

假设您没有输入部门名称,请按submit,您将看到错误消息


请记住,页面的
模型必须是
DepartmentViewModel
。在上面的示例中,它不是。您正在重定向,因此modelstate不存在了。您可以通过tempdata保存它,但我不会那样做()。您可以使用特殊字段和一些通知消息(例如toastr)显示错误,或者只是停留在同一视图上,然后显示modelstate错误

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");
}

尝试添加@glosrob like建议的验证摘要

@using (Html.BeginForm()) 
{
   @Html.ValidationSummary()
...
还可以使用
ValidationMessageFor

<td>
     @Html.DisplayFor(modelItem => item.DepartmentName)
     @Html.ValidationMessageFor(v=>v.DepartmentName)
 </td>

@DisplayFor(modelItem=>item.DepartmentName)
@Html.ValidationMessageFor(v=>v.DepartmentName)

您是否发生了验证错误,或者您只是想输出一些错误?实际上,我想在部门列表视图中显示控制器抛出的错误消息。请您详细说明一下。我没有明白你的意思。请转到我答案中的链接;重定向时不会持久化ModelState。您正在缓存错误,将其放入MealStand中,但在->之后重定向。您需要继续MyDealStand(链接中的解决方案),但我会考虑重构它。另外,我会对你的代码做一些修改(让delete操作帖子,让elmah记录错误-用try-catch调试会很困难…)
<td>
     @Html.DisplayFor(modelItem => item.DepartmentName)
     @Html.ValidationMessageFor(v=>v.DepartmentName)
 </td>