2017-07-31 64 views
-1

我有一個模型從控制器傳遞到我的asp.net mvc5網站查看。然後我使用模型顯示下拉列表,並且我想在提交表單時傳回一個id。這裏是我的模型:傳遞參數從Htmldropdownlistfor控制器

public class SiteDirectionModel 
{ 
    public int id { get; set; } 
    public string name { get; set; } 
} 

然後在模型中,我用一個List<SiteDirectionModel>,而我每添加一個I需要項目的新實例。我填寫這兩個列表,然後將我的模型傳遞給視圖。

@model List<SiteDirectionModel> 

@using (Html.BeginForm("GetSiteRF", "Create", FormMethod.Post)) 
{ 
    @Html.DropDownListFor(x => x.name,new SelectList(Model.name,"Sites")); 
    <input type="button" value="Selectionner" class="btn btn-primary"/> 
} 

那麼如何檢索每個name的ID?以及如何將它作爲參數傳遞給我的控制器?這樣,我會:

public ActionResult GetSiteRF(int id) 
{ 
    int newId = id; 
    //Call method to searchId ... 
    return View("CreateADUser"); 
} 
+0

是的,正是你的模型是不是看起來很不錯。 –

+0

'DropDownListFor()'綁定到,並回傳一個值,而不是一組值。而且你不能爲你綁定的屬性和'SelectList'使用相同的名稱。並且你的參數被命名爲'id',但是你沒有'name =「id」' –

+0

的表單控件。你是指每個'name'的id? (name是一個'string',它沒有一個id) –

回答

1

我已經給出瞭如何綁定並從下拉獲得價值。請在這裏使用你自己的BL。

您的模型應該是這樣的。

public class Something 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

public class SiteDirectionModel 
{ 
    public SelectList MyDropDown { get; set; } 

    public int SelectedValue { get; set; } 
} 

你BL應該是這樣的。

public List<Something> GetListofSomething() 
{ 
    //your logic. 

} 

你的Get方法應該是這樣的。

public ActionResult MyGetMethod() 
    { 
     SiteDirectionModel model = new SiteDirectionModel(); 
     model.MyDropDown = new SelectList(GetListofSomething(), "key_field_name", "value_field_name", "default_value"); 
    } 

後來終於HTML

@Html.DropDownListFor(x => x.SelectedValue,Model.MyDropDown)