【发布时间】:2015-08-08 15:56:59
【问题描述】:
本月列表已添加到数据库中。对于添加工资(创建操作),我必须从下拉列表中选择月份类型,如果未选择月份,则程序不应重定向以创建操作。如何在路由创建操作之前验证下拉列表?
@using(Html.BeginForm("Create","Talab",FormMethod.Post))
{
<div class="row">
<div class="form-group">
<div class="col-md-2">
<a href="@Url.Action("Create","TotalSalary")" class="btn btn-success input-sm">Add New </a>
</div>
</div>
<div class="form-group">
<div class="col-md-2">
@Html.DropDownListFor(model => model.Month.id, (IEnumerable<SelectListItem>)ViewData["monthType"], "--Select a Month--")
@Html.ValidationMessageFor(model => model.Month.id)
</div>
</div>
</div>
}
我的视图模型有以下属性
public class Salary
{
public int id { get; set; }
public Nullable<int> month_id { get; set; }
[Required]
public virtual Month Month { get; set; }
public IEnumerable<Month> GetMonths()
{
IEnumerable<Month> mat = null;
mat = this.db.Months.ToList();
return mat;
}
}
Public Class Month
{
public int id { get; set; }
public string month { get; set; }
public virtual ICollection<Salary> Salary { get; set; }
}
我的控制器动作索引
public ActionResult Index()
{
Salary salary = new Salary();
ViewData["monthType"] = salary .GetMonths().ToList().Select(
s => new SelectListItem
{
Text = s.month,
Value = s.id.ToString()
});
return View(salary);
}
【问题讨论】:
-
顺便说一句,强烈建议您干净地格式化您的代码,以便人们可以快速准确地了解您在做什么!
-
只需像任何其他输入一样使用RequiredAttribute。验证与下拉列表或文本框或您使用的任何输入无关。
-
不 它没有工作!我可以在不从下拉列表中选择任何值的情况下重定向到创建操作。
-
如果我理解正确,如果下拉列表中未设置月份,您是否希望禁用创建链接?然后你必须使用 javascript 进行验证。
-
是的!正是......请帮助解决这个问题