2015-12-04 82 views
0

我想在佈局中調用模型以在空文本字段中使用驗證,以便在任何字段爲空時向用戶返回錯誤。我有一個代碼佈局如何在mvc 4 razor中調用模型佈局

@using (Html.BeginForm("Sending", "Home")) 
{ 
<form method="post" id="contactfrm" role="form"> 
    <div class="col-sm-4"> 
    <div class="form-group"> 
     <label for="name">Name</label> 
     @Html.TextBoxFor("Name", null, new { id = "name", @class = "form-control", placeholder = "Enter name", title = "Please enter your name (at least 2 characters)" }) 
@Html.ValidationMessageFor(model => model.Name) 
     </div> 
     <div class="form-group"> 
     <label for="email">Email</label> 
     @Html.TextBoxFor("Email", null, new { id = "email", @class = "form-control", placeholder = "Enter email", title = "Please enter a valid email address)" }) 
     @Html.ValidationMessageFor(model => model.Email) 
     </div> 
    </div> 
    <div class="col-sm-4"> 
<div class="form-group"> 
<label for="comments">Comments</label> 
@Html.TextArea("Comment", null, new { id = "comments", @class = "form-control", TextMode = "MultiLine", Columns = "3", Rows = "5", placeholder = "Write you message here...", title = "Please enter your message (at least 10 characters)", Style = "resize:none" }) 
@Html.ValidationMessageFor(model => model.Comment) 
</div> 
    <button name="submit" type="submit" class="btn btn-lg btn-primary" id="submit">Send Your Message</button> 
    <div class="result"></div> 
    </div> 
    </form> 
} 

我想打電話給sending.cs使用模型@ Html.ValidationMessageFor(型號=> model.Name)

我怎麼能調用模型的佈局?

謝謝

+0

那麼當你將@ Html.ValidationMessageFor(model => model.Name)添加到你的代碼時會發生什麼? – hjardine

+0

其他方式將添加「必需的」HTML屬性 – evictednoise

回答

1

模型添加到您瀏覽網頁這樣

@model nameOfModel 

,並使用它像這樣

@Html.ValidationMessageFor(model => model.Name) 

,如果你希望只使用它的porperty做它是這樣的

@Model.nameOfproperty 
+0

我知道它可以與其他視圖一起工作,但現在我想我必須做一個基於jQuery的驗證,它可以在移動take或muse輸入事件後知道我驗證 – developer