2014-08-28 42 views
0

我有一個視圖的代碼,其中我從3個不同的文本框中提交一些數據。這只是我創建的練習示例。我在ASP.Net中使用MVC4的Razor語法。在ASP.Net MVC4驗證未綁定的文本框

我的問題:如何驗證文本框,以便始終需要它們?

@{ 
    ViewBag.Title = "HelloWorld"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

<h2>HelloWorld</h2> 
<div>This is a sample Hello World page</div> 
<h1>@ViewBag.Title</h1> 
<h2>@ViewBag.Message</h2> 
@using (Html.BeginForm("HandleSubmit", "Home")) 
{ 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary() 

    <fieldset> 
     <legend>Registration Form</legend> 
     <ol> 
      <li> 
       @Html.Label("username", "UserName") 
       @Html.TextBox("username") 
      </li> 
      <li> 
       @Html.Label("pwd", "Password") 
       @Html.Password("pwd") 
      </li> 
      <li> 
       @Html.Label("cpwd", "Confirm Password") 
       @Html.Password("cpwd") 
      </li> 
     </ol> 
     <input type="submit" value="TestPost" /> 
     <div style="color:red;font-weight:bold">@ViewBag.Feedback</div> 
    </fieldset> 
} 

UPDATE 1:的另一種方法來驗證文本框和顯示自定義無效消息是如下。

@Html.TextBox("username", null, new { @required = "required", 
@oninvalid = "this.setCustomValidity('This data is a must')" }) 
+0

MVC的模板是什麼你的意思是_unbound textboxes_?這些不是模型中的屬性? – 2014-08-28 04:02:13

+0

它不受模型中的任何屬性限制。 – Sunil 2014-08-28 04:03:05

回答

1

坐落在HTML所需的屬性屬性參數輔助

@Html.TextBox("username", null, new { @required="required", @oninvalid="setCustomValidity('I\'m required')" }) 

要定製這一點,並獲得同樣的效果,因爲你需要jquery.validate.jsjquery.validate.unobtrusive.js

@Html.TextBox("username", null, new { @data_val_required="I'm required", @data_val="true" }) 
<span data-valmsg-replace="true" data-valmsg-for="username"></span> 
+0

感謝您的回答。對於上述情況,我將如何顯示自定義消息而不是標準消息? – Sunil 2014-08-28 04:08:43

+0

我已將此添加到我的答案 – Shoe 2014-08-28 04:18:51

+0

我使用了另一種格式來自定義驗證消息,如我的原始帖子的UPDATE 1中所示。這對你看起來好嗎?它似乎在IE 11中工作。 – Sunil 2014-08-28 04:22:14