2011-03-03 30 views
0

我无法弄清楚如何从下拉列表发送参数到我的模型。有人能告诉我一个如何做到这一点的例子吗?html帮手方法的问题

+1

请发表更多信息。一些示例代码? – 2011-03-03 15:39:21

回答

2

与往常一样,你首先来定义模型:

public class MyViewModel 
{ 
    public string SelectedValue { get; set; } 

    public SelectList Items 
    { 
     get 
     { 
      return new SelectList(new[] 
      { 
       new SelectListItem { Value = "1", Text = "item 1" }, 
       new SelectListItem { Value = "2", Text = "item 2" }, 
       new SelectListItem { Value = "3", Text = "item 3" }, 
      }, "Value", "Text"); 
     } 
    } 
} 

控制器:

public class HomeController: Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new MyViewModel(); 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(MyViewModel model) 
    { 
     // You will get the selected value inside model.SelectedValue here 
     // => do something with it 
     .... 
    } 
} 

强类型的视图:

<% using (Html.BeginForm()) { %> 
    <%= Html.DropDownListFor(x => x.SelectedValue, Model.Items) %> 
    <input type="submit" value="OK" /> 
<% } %> 
+0

谢谢达林我认为我没有提出正确的方式问题因为下拉列表从DB上的表格取值问题是如何发送选定的valut作为参数thnx – 2011-03-03 15:44:48

+2

@meti,然后使问题正确。 – 2011-03-03 16:10:16

0
public ActionResult Edit(int id) 
     { 
      Affiliate affiliate = affiliateRepository.GetAffiliate(id); 
      List<SelectListItem> StateList = new List<SelectListItem>(); 
      SelectListItem item; 

      Dictionary<string, string> dictState = S127Global.Misc.getStates(); 


      foreach (KeyValuePair<string, string> k in dictState) 
      { 
       item = new SelectListItem(); 
       item.Text = k.Value; 
       item.Value = k.Key; 
       StateList.Add(item); 
      } 
      item = new SelectListItem(); 
      item.Text = " - Select State - "; 
      item.Value = ""; 
      StateList.Insert(0, item); 


      //create new select list with affiliate.state as the selected value in ViewData 
      ViewData["State"] = new SelectList(StateList.AsEnumerable(), "Value", "Text",affiliate.State); 
      return View(affiliate); 
     } 

的观点

代码
<div class="editor-label"> 
    <%: Html.LabelFor(model => model.State) %> 
</div> 
<div class="editor-field"> 
    <%: Html.DropDownList("State")%> 
    <%: Html.ValidationMessageFor(model => model.State) %> 
</div>