首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在asp.net mvc3中显示错误消息

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

Stack Overflow用户
提问于 2013-03-13 02:18:18
回答 3查看 5.4K关注 0票数 0

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

这是我的视图模型:

代码语言:javascript
运行
复制
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; } 
}

这是控制器:

代码语言:javascript
运行
复制
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");
    }
}

这是View:

代码语言:javascript
运行
复制
@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 "),但错误消息没有显示在那里。

EN

回答 3

Stack Overflow用户

发布于 2013-03-13 02:48:58

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

代码语言:javascript
运行
复制
@using (Html.BeginForm())
{
    <form class="form-horizontal">

@Html.BeginForm会为您处理form标记。

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

代码语言:javascript
运行
复制
@using (Html.BeginForm())
{
    @Html.ValidationSummary()
    <fieldset>

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

将引用添加到

代码语言:javascript
运行
复制
jquery
jquery.validate.js
jquery.validate.unobtrusive.j

CDN可以在here上找到

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

请记住,页面的model必须为DepartmentViewModel。在上面的例子中,不是这样的。

票数 1
EN

Stack Overflow用户

发布于 2013-03-13 02:52:52

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

代码语言:javascript
运行
复制
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");
}
票数 1
EN

Stack Overflow用户

发布于 2013-03-13 03:01:31

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

代码语言:javascript
运行
复制
@using (Html.BeginForm()) 
{
   @Html.ValidationSummary()
...

也可以使用ValidationMessageFor,比如

代码语言:javascript
运行
复制
<td>
     @Html.DisplayFor(modelItem => item.DepartmentName)
     @Html.ValidationMessageFor(v=>v.DepartmentName)
 </td>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15369011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档