简体   繁体   English

ValidationMessage ASP.NET MVC

[英]ValidationMessage asp.net mvc

I have a question about ModelState.AddModelError method and about the ValidationMessage method. 我对ModelState.AddModelError方法和ValidationMessage方法有疑问。

I am new to ASP.NET MVC and I am a little confused. 我是ASP.NET MVC的新手,我有些困惑。

I wrote this code: 我写了这段代码:

public ActionResult update(FormCollection collection)
{
    int oos = 0;

    try
    {
        oos = int.Parse(collection[0]);
    }
    catch
    {         
    }

    data d = new data();

    TryUpdateModel(d , collection.ToValueProvider());

    if (ModelState.IsValid)
    { 
         return View("index",d);
    }
    else
    {      
        ModelState.AddModelError("Date", "Wronge Date");   
        d.Id = 50;
        return View("index",d);
    }
}

and this code in the view side 而此代码在视图侧

@{

    ViewBag.Title = "index";
}

<h2>index</h2>
@TempData["Hi"]

@Html.ValidationMessage("fullname") 

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken() @Html.TextBox("id", 70) 
    @Html.TextBox("Date", "3/2/1991 12:00:00 ص")
    @Html.ValidationMessage("Date","Please insert the correct Date Format") 

    <input type="submit"> 
}

My questions are, why the message Please insert the correct Date Format appears directly when I rune the index while still I did not submit the form, why when I submit the form with error in the date format,the same message appear but not the message that I set to the Date Key in the update method which is Wronge Date . 我的问题是,为什么在我仍未提交表单时运行索引时直接出现“ 请插入正确的日期格式 ”消息,为什么当我提交日期格式有误的表单时却出现相同的消息却没有出现我在Wronge Date的更新方法中将其设置为Date键。

maybe still I do not understand those two methods so I hope to find somebody to explain them to me. 也许我还是不理解这两种方法,所以我希望找人向我解释。

explnation with example or reference would be appreciated 与示例或参考的解释将不胜感激

Please look at http://www.asp.net/mvc/overview/getting-started/introduction/adding-validation 请查看http://www.asp.net/mvc/overview/getting-started/introduction/adding-validation

Because you have already entered a message in the View it will use that over your error that you are adding from the controller. 因为您已经在视图中输入了一条消息,所以它将用于您从控制器添加的错误中。 As for your fullname you do not have a message set yet, only the placehoder for the field. 至于您的全名,您尚未设置任何消息,仅该字段的占位符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM