2017-04-13 66 views
0
@using (Html.BeginForm()) 
    { 
    <p> 
     Search By: @Html.TextBox("SearchString") 
     @Html.RadioButton("searchByOption", "Load Id")<text>Load Id</text> 
     @Html.RadioButton("searchByOption", "User Id")<text>User Id</text> 
     <input type="submit" value="Search" /> 
    </p>  
    } 

我想在運行視圖之前在我的index.cshtml文件中驗證文本框的內容。如果文本框是空白的並且他們按下了搜索按鈕,我可以輕鬆地回覆一條消息「在搜索前在文本框中輸入一個值」?驗證文本框的內容

回答

1

您應該使用強類型的視圖模式,將會使工作變得更容易,你的模型看起來像:

public namespace YourNamespace.Models 
    public class SearchModel 
    { 
     [Required(ErrorMessage = "Enter a value in the textbox prior to searching")]   
     public string Term 
     // other properties here 
    } 
} 

現在查看指定模型,並用TextBoxFor,與使用ValidationMessageFor幫手來顯示在Model屬性應用於Required屬性錯誤消息:

@model YourNamespace.Models.SearchModel 
@using (Html.BeginForm("ActionName","ControllerName",FormMethod.Post)) 
{ 
<p> 
    Search By: @Html.TextBoxFor(x=> x.Term) 
    @Html.ValidationMessageFor(x=>x.Term) 
    @Html.RadioButton("searchByOption", "Load Id")<text>Load Id</text> 
    @Html.RadioButton("searchByOption", "User Id")<text>User Id</text> 
    <input type="submit" value="Search" /> 
</p> 
} 

和控制器,你需要檢查模型狀態,如果它不是有效的發送模型對象返回查看其他執行再quired業務邏輯和數據庫opertation:

public class YourController : Controller 
{ 

    public ActionResult YourAction(SearchModel model) 
    { 

    if(ModelState.IsValid) 
    { 
     // perform search here 
    } 
    else 
    { 
     return View(model); // send back model 
    } 

    } 

} 

請看看following blogpost here這可能是有益的。

+0

謝謝,這非常有幫助! – DiaGea