I have a model and that model has a public List<string> Hour { get; set; }
and the constructor
public SendToList()
{
Hour = new List<string> { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" };
}
My question is why don't I get a selected value for this
@Html.DropDownListFor(model => model.Hour, Model.Hour.Select(
x => new SelectListItem
{
Text = x,
Value = x,
Selected = DateTime.Now.Hour == Convert.ToInt32(x)
}
))
But I get a selected value here.
@Html.DropDownList("Model.Hour", Model.Hour.Select(
x => new SelectListItem
{
Text = x,
Value = x,
Selected = DateTime.Now.Hour == Convert.ToInt32(x)
}
))
What is the difference?
You can not set the "SelectedValue" declaratively, but by saying "SelectedValue=<%# [code here] %> you are effectively causing the value to be set when the control is data bound.
After passing the data now to display it in the View. For that add a View by right-clicking inside ActionResult and select AddView and provide its name as Index. After adding the View add a Namespace to the Model as shown below. Here we can directly access the MobileList from the Model.
IEnumerable<SelectListItem> list = items. Select(c => new SelectListItem { Text = c. CURRENCY_SYMBOL, Value = c. ID.
You can bind a selected value from the drop-down list using the ngModel and edit it inside the text box or numeric input box. The selected item text and value can be got using the change event of the drop-down list through the args. itemData.
Because you need to assign the selected value to your model.
So I would recommend you the following approach. Let's start with the view model:
public class MyViewModel
{
// this will hold the selected value
public string Hour { get; set; }
public IEnumerable<SelectListItem> Hours
{
get
{
return Enumerable
.Range(0, 23)
.Select(x => new SelectListItem {
Value = x.ToString("00"),
Text = x.ToString("00")
});
}
}
}
you could populate this view model inside the controller:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// Set the Hour property to the desired value
// you would like to bind to
Hour = DateTime.Now.Hour.ToString("00")
};
return View(model);
}
}
and in your view simply:
@Html.DropDownListFor(
x => x.Hour,
new SelectList(Model.Hours, "Value", "Text")
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With