How to get checked flag list values ​​in asp.net mvc 3 with a strongly typed view?

Keywords: asp.net mvc 3, list of flags, strongly typed view.

So, please do not suggest me to use ViewBag or formcollection.

I'm not new to web form development, but I'm pretty new to asp.net MVC.

Suppose on the registration page I have something like this:

A very simple registration form

What does the view model look like? Does the following look right?

public class RegistrationViewModel

{

// To store the selected state ID upon postback.
public int StateId {get; set; }  

// A list of states to populate the dropdown.
public Dictionary<int, string> States {get; set; } 

// To store the list of insurance companies the user has used before.
public int[] PriorInsuranceCompanies {get; set; } 

// A list of insurance companies to populate the check box list.
public Dictionary<int, string> InsuranceCompanies {get; set; }

}

, , , , . , . mvc-, ? ( )? .

+3
1

. viewmodels ViewBag.

MultiSelectList, .

public IList<int> PriorInsuranceCompaniesSelected { get; set; }
public MultiSelectList PriorInsuranceCompanies { get; set; }

, (, , ), .

Get ( ):

  model.PriorInsuranceCompaniesSelected = new List<int>();
  var companies = repository.GetPriorInsuranceCompanies();
  //add to your PriorInsuranceCompaniesSelected the values already checked from your entity
  var entity = repository.GetEntityBy(id);
  if (entity.PriorInsuranceCompanies != null)
    foreach (var item in entity.PriorInsuranceCompanies)
      model.PriorInsuranceCompaniesSelected.Add(item.Id);

  var select = (from s in companies select new { Id = s.Id, Name = s.Name }).OrderBy(x => x.Name); //.ToList;
  model.PriorInsuranceCompanies = new MultiSelectList(select, "Id", "Name", model.PriorInsuranceCompaniesSelected);

Html

@foreach (var item in Model.PriorInsuranceCompanies)
{
   <label for="@item.Value" class="check">
   <input type="checkbox" id="@item.Value" name="PriorInsuranceCompaniesSelected" value="@item.Value" @(item.Selected ? "checked" : "") />@item.Text</label>
}

ModelBinder . model.PriorInsuranceCompaniesSelected

[HttpPost]
public ActionResult MyForm(MyViewModel model)
{
  if (ModelState.IsValid)
  {
    try
    {
      //your mapping code or whatever...

      //You do your things with the selected ids..
      if (model.PriorInsuranceCompaniesSelected != null && model.PriorInsuranceCompaniesSelected.Count > 0)
        entity.PriorInsuranceCompanies = repository.GetCompaniesBy(model.PriorInsuranceCompaniesSelected);
      else
        entity.PriorInsuranceCompanies = new List<Comapny>();
      repository.Save(entity);

      return RedirectToAction("Index");
    }
    catch (RulesException ex)
    {
      ex.CopyTo(ModelState);
    }
    catch
    {
      ModelState.AddModelError("", "My generic error taken form a resource");
    }
  }

  //rehydratates the list in case of errors
  //....
  return View(model);
}

, . ,

+4

All Articles