Reputation: 10713
I have this code:
columns.ForeignKey(p => p.SomeProperty, new SelectList(new[] { "0", "1", "2", "3", "4", "5" }));
And I want to populate the SelectList
dinamically, not always from 0 to 5. Let's say I have the upper limit saved in a Session["upperLimit"]
variable. How to create a for loop in the view, so that the SelectList
will go from 0 to Session["upperLimit"]
?
Upvotes: 0
Views: 151
Reputation: 56429
Well for starters, don't put the upper limit in the Session
, if you need it in the view, the Model
is the perfect use case for this. Secondly, the SelectList
should also be contained in the Model
really, saves you putting logic in the view and that means you don't even need the Limit
in the Model
.
Say your Model has these properties:
public class MyModel
{
public string SomeProperty { get; set; }
public SelectList MyNumbers { get; set; }
}
Then your controller action could do something like:
public ActionResult Index(int upperLimit) //I'm assuming that's where the limit is
{
var model = new MyModel();
model.MyNumbers = new SelectList(Enumerable.Range(0, upperLimit + 1));
return View(model);
}
Then in your view do:
@Html.DropDownListFor(m => m.SomeProperty, Model.MyNumbers)
Upvotes: 1
Reputation: 35126
I would create the select list in the Controller and pass it to the view instead. View is for iterating the model. The business logic should be in controller.
However if you still want to do this in view you can do something like the following:
@{
var list = new SelectList(Enumerable.Range(0, (int)Session["upperLimit"] + 1));
columns.ForeignKey(p => p.SomeProperty, list);
}
Upvotes: 1