我想知道在強類型視圖中是否可以將jQuery與@ Html.DropDownListFor結合起來,因爲我開始懷疑它不是,或者我的方法這個問題是有缺陷的。使用jQuery填充DropDownListFor
型號:
public class NewUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public string ConfirmEmail { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public SelectListItem DOBDay { get; set; }
public SelectListItem DOBMonth { get; set; }
public SelectListItem DOBYear { get; set; }
public string Gender { get; set; }
}
查看:
@model test.Models.NewUser
@using (Ajax.BeginForm("RegisterUser", "Register", new AjaxOptions { OnSuccess = "" }))
{
<div>
@Html.TextBoxFor(m => Model.FirstName, new { @class = "big_i", @watermark = "First name" })
@Html.TextBoxFor(m => Model.LastName, new { @class = "big_i", @watermark = "Last name" })
</div>
<div>
@Html.TextBoxFor(m => Model.EmailAddress, new { @class = "big_i long_i", @watermark = "E-mail address" })
</div>
<div>
@Html.TextBoxFor(m => Model.ConfirmEmail, new { @class = "big_i long_i", @watermark = "Confirm e-mail address" })
</div>
<div>
@Html.PasswordFor(m => Model.Password, new { @class = "big_i long_i", @watermark = "Password" })
</div>
<div>
@Html.PasswordFor(m => Model.ConfirmPassword, new { @class = "big_i long_i", @watermark = "Confirm password" })
</div>
<div>
<fieldset>
<h2>
Date of birth</h2>
<div id="reg_date_control" class="date_control">
@Html.DropDownListFor(m => Model.DOBDay, Enumerable.Empty<SelectListItem>(), "Day: ", new { @class = "dc-days big_i" })
@Html.DropDownListFor(m => Model.DOBMonth, Enumerable.Empty<SelectListItem>(), "Month: ", new { @class = "dc-months big_i" })
@Html.DropDownListFor(m => Model.DOBYear, Enumerable.Empty<SelectListItem>(), "Year: ", new { @class = "dc-years big_i" })
</div>
</fieldset>
</div>
}
表單控制器行動提交:
[HttpPost]
public ActionResult RegisterUser(Models.NewUser model)
{
string firstName = model.FirstName;
string lastName = model.LastName;
string email = model.EmailAddress;
string confirm_email = model.ConfirmEmail;
string password = model.Password;
string confirm_password = model.ConfirmPassword;
string dob_month = model.DOBMonth.Value; // an error is raised here
return View();
}
我想最初綁定@ Html.DropDownListFor對空列表,然後jQuery將填充它。我不會在這裏粘貼jQuery代碼,它基本上是填充每個DOB下拉列表,並顯示選定月份的有效天數。
列表填充正常。但是,DOBDay,DOBMonth和DOBYear始終爲空。我想到的是使用Enumerable.Empty()是我的問題,不過話說回來,我已經試過填充像這樣的下拉菜單:
@model gs_mvc.Models.NewUser
@{
string[] months = new[]{"January", "February", "March", "April", "etc"};
var items = new List<SelectListItem>();
for (int i = 0; i < months.Length; i++) {
items.Add(new SelectListItem { Value = i.ToString(), Text = months[i] });
}
}
...
@Html.DropDownListFor(m => Model.DOBMonth, items, "Month: ", new { @class = "big_i" })
這也給了一個空值。
在這一點上,我相信我最好的選擇是將我的jQuery腳本的功能移到C#中,並且每次更改下拉列表時都會執行AJAX調用。不過,我想首先在這裏檢查一下,我不會錯過那些讓我做我想做的事的盲目顯而易見的東西。
是的,這是問題所在。我知道這會很簡單。非常感謝你。 – nullseifer