Html.DropDownList剃刀

时间:2015-01-10 13:40:28

标签: asp.net asp.net-mvc list asp.net-mvc-4 razor

我是MVC和C#的新手,并且在下拉列表中遇到了困难。

我想要完成的是使用保存设置的对象初始化我的页面 (我从XML文件中读取设置)。

这是我拥有的

public class StoreSettings  
{  
    public String BackSrs2Path { get; set; }  
    public int NoLines { get; set; }  
    public String Requesturl { get; set; }  
}  

public class Store  
{  
    public String StoreId { get; set; }  
    public String Address { get; set; }  
    public StoreSettings StoreSettings { get; set; }  
}  

我的视图模型页面是Store

的列表
@model System.Collections.Generic.List<Control2.Models.Store>  
@{     
List<SelectListItem> selectList = new List<SelectListItem>();  
foreach (var Store in Model)  
{  
SelectListItem i = new SelectListItem();  
i.Text = Store.StoreId;  
i.Value = Store.StoreId;  
selectList.Add(i);  
}  
 }  
 @using (Html.BeginForm())  
{  
 SelectList list = new SelectList(selectList, "Value", "Text");  
 @Html.DropDownList("ddl", list, "select store", new { onchange = "this.form.submit();" });  
  }  
  } 

通过阅读这里的示例设法填充我的模型和postback中的下拉列表 但现在我只需要从列表中获取所选对象,并将他的seetings应用到页面上以显示它等消息&#34;您已选择Store&#34; + Storeid(从下拉列表中选择)

此代码也是在我的cshtml页面中编写的,该页面不是最好的,但无法解决我应该如何使用ViewModel和下拉列表

1 个答案:

答案 0 :(得分:2)

是的,当我第一次看到MVC的DropDownList绑定机制时,我也遇到了问题。我想做的是向您提出以下建议:

创建一个Viewmodel并将整个视图绑定到viewmodel ...,如下所示:

public class VMStore
{
    public VMStore()
    {
        ItemsInDropDown = new List<SelectListItem>(){
            new SelectListItem{ Text="SomeValue", Selected=false, Value="SomeUniqueId"}
        };

    }
        public String StoreId { get; set; }
        public String Address { get; set; }
        public StoreSettings StoreSettings { get; set; }
        public string SelectedValue { get; set; }
        public IEnumerable<SelectListItem> ItemsInDropDown { get; set; }
        public void Post()
        {
           //This method will have the user selected value...

        }

}

该视图将绑定如下字段:

    @model WebApplication1.ViewModels.VMStore

    @{
        ViewBag.Title = "GetStore";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }

    <h2>GetStore</h2>

    <div>
        <h4>VMStore</h4>
        <hr />
        <dl class="dl-horizontal">

            @Html.BeginForm(){
            <dt>Select Store</dt>

            <dd>@Html.DropDownListFor(p=>Model.SelectedValue, Model.ItemsInDropDown) </dd>

            <dd><button type="submit">Submit</button></dd>
            }        

        </dl>
    </div>

动作方法如下所示:

    public ActionResult GetStore()
    {
        return View();
    }
    [HttpPost]
    public ActionResult GetStore(ViewModels.VMStore userdata) {
        if (ModelState.IsValid)
        {
            userdata.Post();
        }
        return View(userdata);

    }
相关问题