まず、以下に 2 つのモデル クラスを示します。
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);
}
私の問題は、ユーザーが情報を入力せずにチェックボタンを押した場合、2 つの入力要素の周りにその赤い四角形を取得する必要がありますが、それが起こらないことです。私が見逃しているアイデアはありますか?