首先,下面是我的两个模型类。
public class DataModel
{
[Required]
public string SubscriptionName { get; set; }
[Required]
public SubscriptionDateModel SubscriptionExpiry { get; set; }
public DataModel()
{
SubscriptionExpiry = new SubscriptionDateModel();
}
}
public class SubscriptionDateModel
{
public int Year { get; set; }
public int Month { get; set; }
public IEnumerable<SelectListItem> Months
{
get
{
var Months = new List<SelectListItem>();
Months.Add(new SelectListItem() { Text = "-----", Value = "0" });
string[] MonthList = new string[12] { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" };
int MonthIndex = 0;
for (var i = 0; i < MonthList.Length; i++)
{
MonthIndex = i + 1;
var item = new SelectListItem()
{
Selected = (Month == MonthIndex),
Text = MonthList[i],
Value = MonthIndex.ToString()
};
Months.Add(item);
}
return Months;
}
}
public IEnumerable<SelectListItem> Years
{
get
{
var Years = new List<SelectListItem>();
Years.Add(new SelectListItem() { Text = "-----", Value = "0" });
string[] YearList = new string[9] { "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020" };
int YearIndex = 0;
for (var i = 0; i < YearList.Length; i++)
{
YearIndex = i + 1;
var item = new SelectListItem()
{
Selected = (Month == YearIndex),
Text = YearList[i],
Value = YearIndex.ToString()
};
Years.Add(item);
}
return Years;
}
}
}
然后我有一个名为 SubscriptionDate.cshtml 的编辑器模板
@model MvcApplication1.Models.SubscriptionDateModel
@Html.DropDownListFor(m => m.Year, Model.Years, new { id = "Year"}) @Html.DropDownListFor(m => m.Month, Model.Months, new { id = "Month"})
我在 Index.cshtml 中使用这个模板如下
@model MvcApplication1.Models.DataModel
@{
ViewBag.Title = "Home Page";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<h2>@ViewBag.Message</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true, "Required field")
<br />
@Html.Label("Subscription Name: ")
@Html.TextBoxFor(m => m.SubscriptionName)
<br />
@Html.Label("Subscription Expiry: ")
@Html.EditorFor(m => m.SubscriptionExpiry, "SubscriptionDate")
<input type="submit" value="Check" />
}
最后在控制器中,我的操作方法定义如下。
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View(new DataModel());
}
[HttpPost]
public ActionResult Index(DataModel model)
{
if (ModelState.IsValid)
{
ViewBag.Message = "Hello world";
}
return View(model);
}
我的问题是,如果用户在没有输入任何信息的情况下点击 Check 按钮,我需要在两个输入元素周围获得那个红色矩形,但它没有发生。有什么我想念的想法吗?