How to read the data from a dropdown in ASP.Net MVC 3

后端 未结 3 884
半阙折子戏
半阙折子戏 2021-01-14 23:30

Step 1:

I\'m using a dropdown to display company locations. The list comes from the Location table.

Step 2:

While the user is registering, the drop

3条回答
  •  时光说笑
    2021-01-14 23:45

    Create a ViewModel for your form

    public class CompanyViewModel
    {
      public int CompanyId { set;get;}
      // Other properties of Company
      public int SelectedLocationId { set;get;}
      public IEnumerable Locations { set;get;}
    }
    

    Assuming you have a Location class like this

    public class Location
    {
      public int Id { set;get;}
      public string Name { set;get;}
    }
    

    In the Register (HTTPGET) Action method, Return a CompanyViewModel object with Locations filled from database to the View

    public ActionReuslt Register()
    {
      CompanyViewModel model=new CompanyViewModel();
      model.Locations =myRepositary.GetAllLocations();
      return View(model);
    } 
    

    Assuming GetAllLocations returns a list of Location objects from your repositary.

    And in the Register View which is strongly typed to CompanyViewModel

    @model CompanyViewModel
    @using(Html.BeginForm())
    {
    
      @Html.DropDownListFor(x=>x.SelectedLocationId,
                         new SelectList(Model.Locations ,"Id",
                         "Name"),"Select Location")
    
      
    }
    

    Now write an HTTPPost actionmethod to handle the form post(when user submits the form)

    [HttpPost]
    public ActionResult Register(CompanyViewModel model)
    {
     if(ModelState.IsValid)
     {
      // You will have selected Location id available in model.SelectedLocationId property now
      //Save and redirect.
     }
     //Model Validation failed. so Let us reload the locations again
     //because HTTP is stateless and ASP.NET MVC is true to HTTP ! :)
     model.Locations =myRepositary.GetAllLocations();
     return View(model);
    }
    

提交回复
热议问题