验证消息MVC

时间:2014-06-22 19:34:49

标签: asp.net-mvc asp.net-mvc-4

我的代码如下,并且不显示错误消息:

Index.cshtml

@model WebApp.Models.OrderItems
@using (Html.BeginForm("SaveToDB", "Home", FormMethod.Post, new { @class = "form-group", role = "form" }))
{

@Html.Partial("Information")

}

部分:Information.cshtml

@model WebApp.Models.OrderItems

<div class="col-lg-4">
    <div class="form-group">
        <label for="input1" class="col-lg-4 control-label">@Html.LabelFor(model => model.CLInfo.ClientName)</label>
        @Html.EditorFor(model => model.CLInfo.ClientName, new { style = "width:250px" })
        @Html.ValidationMessageFor(model => model.CLInfo.ClientName)
    </div>
</div>

型号:

public class OrderItems
 {
      public InfoCLInfo{ get; set; }
 }

模型:Infos的类

public class Info
 {
     [Display(Name = "Client Name")]
     [Required]
     public string ClientName{ get; set; }    
 }

控制器

    [HttpPost]
    [MultipleButton(Name = "action", Argument = "SaveToDB")]
    public ActionResult SaveToDB(OrderItems Client)
    {
      var errors = ModelState.Values.SelectMany(v => v.Errors);
        if (ModelState.IsValid)
        {
            if (_db == null)
                _db = new OrderDB();

            OrderItems ClientOrig = Session["Clientobj"] as OrderItems;
            ClientOrig.CLInfo = Client.CLInfo;

            Session["Clientobj"] = null;
        }

        return RedirectToAction("Index", "Home");
    }

    [Authorize]
    public ActionResult Index (OrderItems Client)
    {
        int ClientID = Convert.ToInt32(Session["Client"]);
        if ClientID == 0)
        {
            ClientID = 2;
            Session["Client"] = ClientID;
        }

        if (Session["Clientobj"] == null)
        {
            Client = new OrderItems();
            Client.CLOrderID = 123;
            Session["Clientobj"] = Client;
        }
        else
        {
            Client = Session["Clientobj"] as OrderItems
        }
        return View(Client);
    }

发布ModelState.IsValid返回false为true,但我没有任何消息告诉用户哪里有错误修复。

我尝试在BeginForm之后添加:@ Html.ValidationSummary(true),但它没有

请知道

由于

1 个答案:

答案 0 :(得分:1)

如果要保留模型状态,则无法使用RedirectToAction。所有错误以及未保存在ModelState对象中的错误,以及当您重定向到操作时,它正在执行新的get操作,该操作以干净的平板开始。

您需要像在原始操作中一样返回视图。