2017-04-13 12 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ファイルのテキストボックスの内容を検証したいと思います。テキストボックスが空白で、検索ボタンを押した場合、「検索する前にテキストボックスに値を入力してください」というメッセージで簡単に返信できますか?それが表示するようにValidationMessageForヘルパーを使用して、モデルを指定し、TextBoxForを使用するビューで今テキストボックスの内容を確認する

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

答えて

1

あなたは仕事がずっと楽になります強く型付けされたビューとモデルを使用する必要があり、あなたのモデルは次のようになります。 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

関連する問題