skylake skylake - 1 year ago 126
C# Question

Create DropDownList in view and pass value to controller - MVC

How do I create a DropDownList with values 1-10(int) in view and pass on the selected value to controller?

UserToReview modle:

public System.Guid Id { get; set; }
public System.Guid UserId { get; set; }
public System.Guid ReviewId { get; set; }
public Nullable<int> Rating { get; set; }


public ActionResult Rating(Guid id) //got its ReviewId from previous page
//so far empty, no clue what to do

return Content("");

Answer Source

1)First Method In View

<select name="YourDropDownValue">
 @for(int i = 1 ; i <= 10 ; i++) 
  <option value="@i">@i</option>

try using this code, In name attribute you have to keep the field name which you want to pass in the controller

In controller this is how you bind dropdown value

  public ActionResult getDropDown(int YourDropDownValue)


2)Second Method Keep this in the controller get

  List<int> Num = new List<int>() { 1,2,3,4,5,6,7,8,9,10 };
  ViewBag.Number = new SelectList(Num);

Now in view

      @Html.DropDownListFor(x => x.YourDropDownValue, ViewBag.Number as SelectList)

if you have no model

      @Html.DropDownList("YourDropDownValue", ViewBag.Number as SelectList)

Now in Controller

  public ActionResult getDropDown(int YourDropDownValue)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download