2016-10-06 7 views
1

すべて、私はASP.net COREで遊んでいます。私は通常の状況でベストプラクティスを見つけようとしています。下のRazorコードは、HTMLでドロップダウを生成しています。ユーザーがリスト内で「その他」を選択すると、jqueryコードが呼び出され、ドロップダウンの後に入力テキストフィールドが追加されます。私の質問は、ドロップダウン値の代わりに入力テキストフィールドを使用してHTTPポストを行うフォームを取得する方法です。前もって感謝します。モデルバインドで特定のドロップダウン値が選択されている場合、ドロップダウンリスト項目の代わりにテキスト入力値を返す方法はありますか?

<div class="form-inline" > 

<select name="Genre" class="form-control form-inline" id="genreselect" > 
     @foreach (var item in Model) 
      { 
       <option>@item</option> 
      } 
      <option>Other</option> 
     </select>    
</div> 

のjQueryコード:

$("#genreselect").change(function() { 
    //$("#genreinput").show(); 
    if ($("#genreselect option:selected").val() === 'Other') { 
     //$('#genreselect').replaceWith('<input type="text" name="state_d" id="state_d">'); 
     $(this).after('<input id="genreinput" class="form-control" type="text" name="Genre" />'); 
     //$(this). 
     //$("#genreinput").show(); 
    } 
    else { 
     $("#genreinput").hide(); 

    } 
}); 

答えて

0

OtherGenreのようなテキスト入力のための別の名前を使用して、ビューモデルにその名前のプロパティを追加します。

サーバー側のロジックで次に
<input id="OtherGenre" class="form-control" type="text" name="OtherGenre" /> 

public class MyViewModel 
{ 
    public string Genre {get; set;} 
    public string OtherGenre {get; set;} 
} 

ジャンルは、新しいプロパティ(あなたが後でそれを表示する必要がある場合、レコードを保存したりするときは、これを行うことができます)からの値をとり、「その他」の場合:

//Either overwrite Genre before saving it 
public ActionResult MyPostAction(MyViewModel model) 
{ 
    if(model.Genre == "Other") model.Genre=model.OtherGenre; 

    // ...save model ... 
} 

//Or apply that logic when displaying it 
<span>@(@Model.Genre=="Other" ? Model.OtherGenre : Model.Genre)</span> 
+0

ありがとうダニエル、私はそれを試して、それは動作します。あなたは男です。ありがとう。 – mslugx

関連する問題