如何在控制器,MVC 4中显示错误消息? [英] How to Display a error message in view from controller,MVC 4?

查看:133
本文介绍了如何在控制器,MVC 4中显示错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨..

我是MVC 4的新手。

我正在使用razor在c#中开发一个简单的MVC 4应用程序。

现在我需要在视图中显示从控制器传来的错误?

我该如何实现?



我的代码:

我的查看代码:

-------------

Hi..
I am new to MVC 4.
I am developing a simple application in MVC 4 using Razor in c#.
Now i need to Display a error in view which is pass from controller?
How can i achieve it?

MY CODES:
MY VIEW CODE:
-------------

@model mvc_cs.Models.FormModels
@using ctrlr = mvc_cs.Controllers.FormController
@{
    ViewBag.Title = "form_edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
    
}
<h2>
    form_edit</h2>


@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
    
        <table>
        <tr>
        <td>
          @Html.DisplayTextFor(model => model.error_msg)
          @Html.ValidationSummary(false)
      
        </td>
        </tr>
        <tr>
        <th>
            @Html.DisplayNameFor(model => model.content_name)
            @Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")   
        </th>
        </tr>
</table>
    
<table>
    <tr>
        <td>
            <input  type="submit" value="Submit" />
        </td>
    </tr>
</table>
}





我的控制器:

----- ---------



MY CONTROLLER:
--------------

[HttpPost]
      public ActionResult form_edit(FormModels model)
      {
          model.error_msg = model.update_content(model);

          TempData["error"] = "fjghsfhgflsh";
          ModelState.AddModelError("error.error", "adfdghdghgdhgdhdgda");
          
          return RedirectToAction("Form_edit", "Form",model.error_msg);
        
      }

推荐答案

您可以使用TemData将上述错误发送给下一个操作方法。在上面重定向的操作方法使用ViewBag来放置上面的错误并将其显示在视图中,如下所示。



行动方法



You can send your error as above using TemData for the next action method.Inside the redirected action method use ViewBag for put above error and show it to the view as below.

Action Method

public ActionResult Form_edit()
{
    ViewBag.Error = TempData["error"];
    return View();
}







查看






View

@ViewBag.Error





查看本文以获取更多选项: 什么是ViewData,ViewBag和TempData? - 用于在当前和后续请求之间传递数据的MVC选项 [ ^ ]


您好,



您可以使用

Hi,

You can use
@if (!ViewData.ModelState.IsValid)
{
      <div>Error description</div>
}



在控制器中


In controller

if (yourError)
{
   ModelState.AddModelError("Error", "Ex: This login failed");
   return View();
}



和查看页面


and in View page

@Html.ValidationMessage("Error")





希望这对你有所帮助。



问候,
RK



Hope this helps you a bit.

Regards,
RK


这篇关于如何在控制器,MVC 4中显示错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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