2016-12-18 24 views
0

@ Html.DropDownListFor要素の使用に問題があります。私が持っているものasp.net mvc Html.DropDownListFor:選択したIDを処理する方法

モデル 'DatabaseModel':

public class DirectionEntity 
{ 
    public string Id { get; set; } 
    public string DirectionName { get; set; } 
} 
public class ViewModel 
{ 
    public int SelectedDirectionID { get; set; } 
    public List<DirectionEntity> DirectionList { get; set; } 
} 

モデル 'のDataFactory':

public class DataFactory 
{ 
    public static ViewModel Refresh() 
    { 
     using (var db = new MyDatabase()) 
     { 
      return new ViewModel() 
      { 
       DirectionList = db.Directions.Select(_ => new { _.Id, _.DirectionName }) 
        .ToList() 
        .Select(_ => new DirectionEntity() { Id = _.Id.ToString(), DirectionName = _.DirectionName }) 
        .ToList(), 
      }; 
     } 
    } 
} 

コントローラー:

public System.Web.Mvc.ActionResult AddNewDocument() 
    { 
     var db = DataFactory.Refresh(); 
     return View(db); 
    } 

    [HttpPost] 
    public System.Web.Mvc.ActionResult AddNewEntry(ViewModel m) 
    { 
      m = DataFactory.Save(m); 
      ModelState.Clear(); 
      return View(<some view>); 
    } 

ビュー:

@using (Html.BeginForm()) 
{ 
@Html.DropDownListFor(m => m.SelectedDirectionID, new  SelectList(Model.DirectionList.Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.DirectionName }), "Value", "Text"), new { @class = "Duration", required = "required" }) 
<button type="submit" class="btn btn-default SaveAll">Save</button> 
} 

質問: ユーザーがドロップダウンリストにいくつかの位置を選択したが、まだPOSTを使用してサーバーに要求を送信した後、「SelectedDirectionID」の値を処理する方法-方法。

+0

投稿方法の前にどのように処理するのかはどういう意味ですか? –

+0

ユーザーがドロップダウンリストの項目を選択すると、この値(つまりSelectedDirectionID値)を処理して別の方法で使用したい –

+0

jqueryを使用してそのアクションメソッドを呼び出す必要があります –

答えて

3

あなたのドロップダウンのIDを確認してから、クライアント側のchangeイベントを購読することができます。これはjQueryを使って行うことができます。

$("#idOfYourDropDown").change(function() { 
    // Do whatever you need to do here 
    // Here are some ways you can get certain things 
    var end = this.value; 
    var selectedText = $(this).find("option:selected").text(); 
    var selectedValue = $(this).val(); 
    alert("Selected Text: " + selectedText + " Value: " + selectedValue); 
}); 

また、あなたはPOSTアクションあなたが道からの眺めを返さない理由で私の答えhereが表示されるはずです。

0

この場合、Jqueryを使用する必要があります。ドロップダウンのビューIDごとに 'SelectedDirectionID'があります。

あなたのJs:

$(document).ready(function() { 
      var selectedValue = $('#SelectedDirectionID').val(); 
      var selectedText = $("#SelectedDirectionID option:selected").text(); 
     }); 

またはインサイド変更イベントをドロップダウン。

$('#SelectedDirectionID').change(function() { 
       var selectedValue = $(this).val(); 
       var selectedText = $(this).find("option:selected").text(); 
      }); 
関連する問題