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?

1
  • try Brendan Vogt solution, it will work Commented May 11, 2012 at 12:21

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Can you share me your Repositaty and GetAllLocations method
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: 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.
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; }
}

6 Comments

Hi What is "locationService" in Locations = locationService.FindAll().Where(x => x.IsActive)
Check my updated answer. locationService is your service layer that can handle any business logic. This is turn calls your repository layer.
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...
Any how i have zero knowledge regarding "Code First" approach and i know "Database First" approach till now...
any how see this once and it it having complete details regarding my problem
|
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"];

3 Comments

Hi Sundal , I Wrote like this,
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
Hi dude it is working and thanks for reply...see this below link once forums.asp.net/t/1803054.aspx/… and reply me if u have any idea

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.