datatest
datatest

Reputation: 473

Turning textbox to a number drop down for an int database column

I have Page Number, and when displaying it on a create new I would like it to show a drop down of 10 numbers. Right now, because it's just an int column, it is showing as a textbox.

What is the easiest way to change this?

Upvotes: 0

Views: 93

Answers (1)

Shyju
Shyju

Reputation: 218822

Add a Collection property to your view model to show the drop down values and one for selected value.

public class CreatePostVM
{
  public string Name { set;get;}
  public List<SelectListItem> Pages { set;get;}
  public int SelectedPage { set;get;}
  public CreatePostVM()
  {
    Pages =new List<SelectListItem>();
  }
}

and in your GET action load the Pages collection of your view model object and send to the view..

public ActionResult CreatePost()
{
  var vm=new CreatePostVM();
  //Adding 1 to 10 as per the question
  for(int i=0;i<10;i++)
  {
     vm.Pages.Add(new SelectListItem { Value=i.ToString(), Text=i.ToString()});
  }
  return View(vm);
}

and in your View, which is strongly typed to the CreatePostVM class

@model CreatePostVM
@using(Html.BeginForm())
{
  <label>Name :</label>  @Html.TextBoxFor(s=>s.Name)
  <label>Page :</label>  @Html.DropDownListFor(s=>s.SelectedPage,Model.Pages)
  <input type="submit" value="Save" />
}

and in your HttpPost action, check the SelectedPage property value.

[HttpPost]
public ActionResult CreatePost(CreatePostVM model)
{
  var pageNumber=model.SelectedPage;
  //do something with the above value
 //to do : Save and Redirect
}

Upvotes: 1

Related Questions