skylake skylake - 2 months ago 27
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; }


Controller:

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

return Content("");
}

Answer

1)First Method In View

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

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

   [HttpPost]
  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

   [HttpPost]
  public ActionResult getDropDown(int YourDropDownValue)
  {


  }