Binding ListBox with a model in MVC3

寵の児 提交于 2019-11-30 22:01:24
Shyju

Add a new Property to your SiteConfig ViewModel of type string array. We will use this to get the Selected item from the Listbox when user posts this form.

public class SiteConfig
{
  //Other properties here
  public string[] SelectedBrands { get; set; }  // new proeprty
  public IEnumerable<SiteBrand> SiteBrands { get; set; }
}

In your GET action method, Get a list of SiteBrands and assign to the SiteBrands property of the SiteConfig ViewModel object

public ActionResult CreateSiteConfig()
{
    var vm = new SiteConfig();
    vm.SiteBrands = GetSiteBrands();
    return View(vm);
}

For demo purposes, I just hard coded the method. When you implement this, you may get the Data From your Data Access layer.

public IList<SiteBrand> GetSiteBrands()
{
    List<SiteBrand> brands = new List<SiteBrand>();
    brands.Add(new SiteBrand { Brand = new Brand { BrandId = 3, Name = "Nike" } });
    brands.Add(new SiteBrand { Brand = new Brand { BrandId = 4, Name = "Reebok" } });
    brands.Add(new SiteBrand { Brand = new Brand { BrandId = 5, Name = "Addidas" } });
    brands.Add(new SiteBrand { Brand = new Brand { BrandId = 6, Name = "LG" } });
    return brands;
}

Now in your View, which is strongly typed to SiteConfig ViewModel,

@model SiteConfig
<h2>Create Site Config</h2>
@using (Html.BeginForm())
{
  @Html.ListBoxFor(s => s.SelectedBrands, 
                new SelectList(Model.SiteBrands, "Brand.BrandId", "Brand.Name"))
  <input type="submit" value="Create" />
}

Now when user posts this form, you will get the Selected Items value in the SelectedBrands property of the ViewModel

[HttpPost]
public ActionResult CreateSiteConfig(SiteConfig model)
{
    if (ModelState.IsValid)
    {
        string[] items = model.SelectedBrands;
        //check items now
        //do your further things and follow PRG pattern as needed
    }
    model.SiteBrands = GetBrands();
    return View(model);
}

You can have a "ViewModel" that has both the site and brand model in it. Then you can bind your view to that model. This would allow you to bind any part of the view to any part of any of the underlying models.

public class siteViewModel{
    public SiteConfig x;
    public Brand b; //Fill this with all the available brands
}

Of course you can include any other information your view might need (reduces the need of ViewBag as well).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!