ASP.net the method for setting the selected item for dropdownlistfor in MVC-practical tips

Source: Internet
Author: User

In MVC, when it comes to a strongly typed edit page, if there is a SELECT element, you need to select one of the selected items based on the value of a property in the current model. This article only to organize ideas, does not involve complete code.

-Train of thought

The type of the Forward view is List<selectlistitem>, the selected property of the SelectListItem check is set to True, and the object instance of that type is put to viewbag. ViewData or model to the foreground view.

By traversing the List<selectlistitem> type object instance

-Controller

Public ActionResult someaction (int id)
{
  //Get domain Model
  var domainmodel from database = Modelservice.loadentities (m => m.id = = ID). Firstordefault<model> ();
 
  Gets the List<selectlistitem> type object instance through a method
  list<selectlistitem> items = SomeMethod ();
 
  Iterates through the collection, setting the SelectListItem selected property to True if one of the properties of the current domain model is equal to the Value property of the SelectListItem
  ( SelectListItem item in items)
  {
    if (item). Value = = Convert.ToString (Domainmodel. a property))
    {
      item. Selected = true;
    }
  }
 
  Put the List<selectlistitem> collection object instance into the ViewData
  viewdata["somekey" = items;
 
  It may involve converting domain model to view model return
 
  Partialview (Domainmodel);


-Foreground View Display

@model Domainmodel
@Html. Dropdownlistfor (M => m.someproperty, (list<selectlistitem>) viewdata["Somekey"], "= = Please select = =")

By traversing the model collection

Set a bool-type field for the view model to describe whether it is selected.
Use some of the properties of model as SelectListItem text and value values. Determine whether to set the SelectListItem selected to True according to the Boolean property in view model.

-view Model

public class Department
{public
  int Id {get;set;}
  public string Name {get;set;}
  public bool IsSelected {Get;set}}

-Controller

Public ActionResult Index ()
{
 Sampledbcontext db = new Sampledbcontext ();
 list<selectlistitem> selectlistitems = new list<selectlistitem> ();
 
 Traverses the Department collection
 foreach (Department Department in db. Departments)
 {
  SelectListItem = new SelectListItem
  {
   Text = department. Name,
   Value = department. Id.tostring (),
   Selected = department. Isselected.hasvalue? Department. IsSelected.Value:false
  }
  selectlistitems.add (SelectListItem);
 }
 viewbag.departments = Selectlistitems;
 return View ();
}

The following are additional users:

Background code:

Public ActionResult Index (formcollection collection)
     {
       ilist<project> li = Utility.SqlHelper.getProjectList ();
       SelectList Selec = new SelectList (li, "ID", "Name");
   
       if (collection["drop"]!= null)
       {
         string projectid = collection[' drop '];
         Selec = new SelectList (li, "ID", "Name", projectid);//To set the selected item  
        viewdata["ruturned"] = collection["Drop" according to the selected item value returned;
       }
       viewdata["Drop"] = Selec;
      return View ();
    }

Front-End Code:

@using (Html.BeginForm ()) {
@Html. DropDownList ("Drop", viewdata["D"] as SelectList)
<input type= "Submit" value= "view the corresponding grouping list"/>
}
<p> current Project ID: @ViewData ["ruturned"]</p>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.