【问题标题】:How to show error message in asp.net mvc3如何在 asp.net mvc3 中显示错误消息
【发布时间】:2013-03-13 03:44:12
【问题描述】:

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

这是我的视图模型:

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

这是控制器:

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

这是视图:

@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>
}

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

【问题讨论】:

  • 您是否发生了验证错误,或者您只是想输出一些错误?
  • 其实我想在Department List视图中显示控制器抛出的错误信息。

标签: c# asp.net asp.net-mvc-3


【解决方案1】:

您正在重定向,所以模型状态消失了。您可以通过 tempdata 保存它,但我不会那样做 (How do I maintain ModelState errors when using RedirectToAction?)。您可以使用特殊字段和一些通知消息(例如 toastr)来显示错误,或者只是停留在同一个视图上,然后会显示模型状态错误。

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

【讨论】:

  • 请您详细说明一下。我没有得到你。
  • 转到我的答案中的链接; ModelState 不会在重定向时保持不变。您正在缓存错误,将其放入模型状态,但在之后重定向 - >您需要保留模型状态(链接中的解决方案),但我会考虑重构它。附言我会对您的代码进行一些更改(进行删除操作发布,获取 elmah 以记录错误 - 使用 try catch 将很难调试...)
【解决方案2】:

首先你有一个重复的表格

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

@Html.BeginForm 为您处理form 标签。

其次,尝试像这样添加@Html.ValidationSummary

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

第三,您需要引用正确的脚本文件。通常这将在布局页面中完成,但这取决于您。

添加对

的引用
jquery
jquery.validate.js
jquery.validate.unobtrusive.j

CDN 可以在here找到

假设您没有输入DepartmentName,请按提交,您应该会看到错误消息。

请记住,您页面的model 必须是DepartmentViewModel。在你上面的例子中它不是。

【讨论】:

    【解决方案3】:

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

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

    也可以使用ValidationMessageForlike

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-03
      • 1970-01-01
      相关资源
      最近更新 更多