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

后端 未结 3 880
半阙折子戏
半阙折子戏 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<Location> 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")
    
      <input type="submit" value="Save" />
    }
    

    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);
    }
    
    0 讨论(0)
  • 2021-01-14 23:52

    It depends how you are getting values of your form if you are passing formcollection then simply you can access its value by this

    public ActionResult MyAction (FormCollection form)
        {
            string value = form["DropDownListName"];
        }
    

    Or you can access it through

    string value = Request.Form["DropDownListName"];
    
    0 讨论(0)
  • 2021-01-14 23:58

    Here is some sample code that you can modify and use in your scenario. I don't know what your code looks like so I created my own.

    In your view:

    @model YourProject.ViewModels.YourViewModel
    

    Your locations dropdown:

    <td><b>Location:</b></td>
    <td>
         @Html.DropDownListFor(
              x => x.LocationId,
              new SelectList(Model.Locations, "Id", "Name", Model.LocationId),
              "-- Select --"
         )
         @Html.ValidationMessageFor(x => x.LocationId)
    </td>
    

    Your view model:

    public class YourViewModel
    {
         // Partial class
    
         public int LocationId { get; set; }
         public IEnumerable<Location> Locations { get; set; }
    }
    

    Your create action method:

    public ActionResult Create()
    {
         YourViewModel viewModel = new YourViewModel
         {
              // Get all the locations from the database
              Locations = locationService.FindAll().Where(x => x.IsActive)
         }
    
         // Return the view model to the view
         // Always use a view model for your data
         return View(viewModel);
    }
    
    [HttpPost]
    public ActionResult Create(YourViewModel viewModel)
    {
         if (!ModelState.IsValid)
         {
              viewModel.Locations = locationService.FindAll().Where(x => x.IsActive);
    
              return View(viewModel);
         }
    
         // If you browse the values of viewModel you will see that LocationId will have the
         // value (unique identifier of location) already set.  Now that you have this value
         // you can do with it whatever you like.
    }
    

    Your location class:

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

    This is simple as can come. I hope this helps :)

    UPDATE:

    My service layer is there for any further business logic and then it calls my repository layer to get the data from the database. I use Entity Framework code first. I also use Autofac for my IoC container.

    Your service layer:

    public class LocationService : ILocationService
    {
         private readonly ILocationRepository locationRepository;
    
         public LocationService(ILocationRepository locationRepository)
         {
              this.locationRepository = locationRepository;
         }
    
         public IEnumerable<Location> FindAll()
         {
              return locationRepository.FindAll();
         }
    }
    

    And your repository:

    public class LocationRepository : ILocationRepository
    {
         YourDbContext db = new YourDbContext();
    
         public IEnumerable<Location> FindAll()
         {
              return db.Locations.OrderBy(x => x.Name);
         }
    }
    

    Your database context class:

    public class YourDbContext : DbContext
    {
         public DbSet<Location> Locations { get; set; }
    }
    
    0 讨论(0)
提交回复
热议问题