在控制器asp.net mvc 5的视图上显示错误消息 [英] Display error message on the view from controller asp.net mvc 5

查看:345
本文介绍了在控制器asp.net mvc 5的视图上显示错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Web开发的新手,试图学习ASP.Net MVC5.如果找不到该记录,那么我正在数据库中寻找一条记录,那么我想向用户显示一条错误消息.以下是我的尝试:

I am new to web development and trying to learn ASP.Net MVC 5. I am looking for one record in database if the record is not found then I want to display an error message to the user. Below is my attempt:

控制器

    [HttpGet]
    public ActionResult Search()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Search(ForgotPasswordMV viewModel)
    {
        if (Temp.Check(viewModel.Email))
            return RedirectToAction("VerifyToken", new { query = viewModel.Email });
        else
        {
            ViewBag.ErrorMessage = "Email not found or matched";
            return View();
        }
    }

查看:

<p>@ViewBag.ErrorMessage</p>

ViewModel

public class ForgotPasswordMV
{
    [Display(Name = "Enter your email"), Required]
    public string Email { get; set; }
}

但是我读到某个地方应该在视图模型中放置一个属性,并在该属性上设置错误消息.我现在很困惑,如何实现该目标以及如何在View中显示错误?推荐/最佳做法是哪一种?

But I read somewhere that I should put one property in my view model and set the error message on that property. I am confused now, how to achieve that and how to display the error in View then? And which one is the recommended/best practice?

推荐答案

但是我读到某处应该在视图模型中放置一个属性 并在该属性上设置错误消息.我现在很困惑,如何 做到这一点,然后如何在View中显示错误呢?哪一个 /最佳做法是什么?

But I read somewhere that I should put one property in my view model and set the error message on that property. I am confused now, how to achieve that and how to display the error in View then? And which one is the recommended/best practice?

最佳做法是像这样更改控制器的ModelState词典属性:

The best practice is to alter the ModelState dictionary property of your controller like this:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Search(ForgotPasswordMV viewModel)
{
    // ... 
    else
    {
        ModelState.AddModelError("Email", "Email not found or matched");
        return View(viewModel);
    }
}

然后在您的视图中,在您的电子邮件字段旁边添加以下行;

Then in your view add the line below next to your email field;

@Html.ValidationMessageFor(m => m.Email)

这篇关于在控制器asp.net mvc 5的视图上显示错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆