2

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 dropdown list will show the locations in question.

When the user selects India, then this value (Location Name) should store in the UserLogin Table.

How can I read the value from the dropdown in ASP.Net MVC 3?

P_A_1
  • 93
  • 2
  • 8

3 Answers3

4

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);
}
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Can you share me your Repositaty and GetAllLocations method – P_A_1 May 12 '12 at 10:41
  • I am doing it by using the Database First but not with Code first approach and please mind it and Repositary and others may not work here... – P_A_1 May 12 '12 at 10:41
  • Please see once here ...http://forums.asp.net/p/1802976/4977669.aspx/1?Re+Read+The+Data+From+DropDown+in+ASP+Net+MVC3 – P_A_1 May 12 '12 at 10:43
  • @P_A_1: Repository is not only used with code first. The idea of repository is to have an abstraction over your data access layer. You can simply replaces that with a call to a your service layer/business layer/data access to get the data. that means =myRepositary.GetAllLocations(); can be a method which returns list of all locations. – Shyju May 12 '12 at 11:46
3

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; }
}
Brendan Vogt
  • 25,678
  • 37
  • 146
  • 234
  • Hi What is "locationService" in Locations = locationService.FindAll().Where(x => x.IsActive) – P_A_1 May 12 '12 at 05:29
  • Check my updated answer. locationService is your service layer that can handle any business logic. This is turn calls your repository layer. – Brendan Vogt May 12 '12 at 06:18
  • Hi, i am new to this MVC concept and in my past i worked on MS CRM and i have less than 15 days age in MVC... – P_A_1 May 12 '12 at 09:53
  • Any how i have zero knowledge regarding "Code First" approach and i know "Database First" approach till now... – P_A_1 May 12 '12 at 09:54
  • any how see this once and it it having complete details regarding my problem – P_A_1 May 12 '12 at 09:55
  • see this link once http://forums.asp.net/t/1802976.aspx/1/10?Read+The+Data+From+DropDown+in+ASP+Net+MVC3 – P_A_1 May 12 '12 at 09:55
1

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"];
Fraz Sundal
  • 10,288
  • 22
  • 81
  • 132
  • Hi Sundal , I Wrote like this, – P_A_1 May 11 '12 at 11:33
  • public ActionResult Index() { ViewBag.OLocation = new SelectList(dbcontext.Organization_Details, "OName", "OLocation"); } and i am calling this OLocation in the Index.cshtml, by using @html.Dropdownlist("OLocation") and now if the user click the submit button then, the value should be selected and then stored into DB... now explain version – P_A_1 May 11 '12 at 11:38
  • Hi dude it is working and thanks for reply...see this below link once http://forums.asp.net/t/1803054.aspx/1?Setting+session+in+MVC+application and reply me if u have any idea – P_A_1 May 13 '12 at 07:17