为选定值MVC 5设置viewbag [英] Set viewbag for selected value MVC 5
本文介绍了为选定值MVC 5设置viewbag的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I am trying to set Selected option to a ViewBag so that when that item is selected specific code is run. It is running only the first item all the item.
我的尝试:
What I have tried:
Below is my code. Any help will be appreciated.
if (RecurringSeries.Weekly == weekly)
{
code goes here
}
else
if (RecurringSeries.Monthly == monthly)
{
code goes here
}
if (RecurringSeries.Weekly == weekly)
{
ViewBag.weekly = weekly;
}
else
{
ViewBag.monthly = monthly;
}
<div class="form-group">
<label>Recurring Series</label>
<select id="ddRecurring" class="form-control">
<option value="@ViewBag.weekly">Weekly</option>
<option value="@ViewBag.monthly">Monthly</option>
</select>
</div>
推荐答案
我希望这对您有用,因为您试图将所选值保留在ViewBag。
I hope this will work for you as you are trying to keep selected value in a ViewBag.
public class UserVM
{
public string Year { set; get; }
public string Month { set; get; }
public string Day{ set; get; }
}
在一个视图包中设置值并绑定
Set value in a viewbag and bind
[HttpGet]
public ActionResult Register(User user)
{
// It should be better to read this data from database
ViewBag.Year = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Text = "1368", Value = "1987" },
new SelectListItem { Text = "1369", Value = "1988"}, //....
}, "Value" , "Text");
// Also other properties like Month and Day
return View();
}
@using (Html.BeginForm())
{
<div class="form-group">
@Html.DropDownListFor(m => m.Year, (SelectList)ViewBag.Year, "Select one")
</div>
<button type="Submit" class="btn btn-success submit">Send</button>
}
获取所选值并将其设置到另一个视图包中。
Get the selected value and set it into another view bag.
[HttpPost]
public ActionResult Register(VM model)
{
if(!ModelState.IsValid)
{
ViewBag.SelectedYear = model.Year;
}
return View();
}
这篇关于为选定值MVC 5设置viewbag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文