我對ASP.net MVC世界頗爲陌生,我試圖弄清楚如何呈現一組複選框,它們是強類型爲視圖模型。在webforms中,我只是使用checkboxlist控件,但我有點與MVC丟失。我如何使用MVC 4和查看模型呈現一組複選框(強類型)
我正在爲婚禮策劃業務構建一個簡單的聯繫表單,並且需要將用戶選擇的任何複選框值傳遞給我的控制器。
形式複選框需要看起來像這樣:
您的幫助將不勝感激。謝謝!
這是我到目前爲止。
控制器
[HttpPost]
public ActionResult Contact(ContactViewModel ContactVM)
{
if (!ModelState.IsValid)
{
return View(ContactVM);
}
else
{
//Send email logic
return RedirectToAction("ContactConfirm");
}
}
視圖模型
public class ContactViewModel
{
[Required]
public string Name { get; set; }
[Required]
public string Phone { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
public string Subject { get; set; }
public IEnumerable<SelectListItem> SubjectValues
{
get
{
return new[]
{
new SelectListItem { Value = "General Inquiry", Text = "General Inquiry" },
new SelectListItem { Value = "Full Wedding Package", Text = "Full Wedding Package" },
new SelectListItem { Value = "Day of Wedding", Text = "Day of Wedding" },
new SelectListItem { Value = "Hourly Consultation", Text = "Hourly Consultation" }
};
}
}
//Not sure what I should do for checkboxes...
}
VIEW
@model NBP.ViewModels.ContactViewModel
@{
ViewBag.Title = "Contact";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm())
{
<div id="ContactContainer">
<div><span class="RequiredField">* </span>Your Name:</div>
<div>
@Html.TextBoxFor(model => model.Name)
</div>
<div><span class="RequiredField">* </span>Your Phone:</div>
<div>
@Html.TextBoxFor(model => model.Phone)
</div>
<div><span class="RequiredField">* </span>Your Email:</div>
<div>
@Html.TextBoxFor(model => model.Email)
</div>
<div>Subject:</div>
<div>
@Html.DropDownListFor(model => model.Subject, Model.SubjectValues)
</div>
<div>Vendor Assistance:</div>
<div>
<!-- CHECKBOXES HERE -->
</div>
<div>
<input id="btnSubmit" type="submit" value="Submit" />
</div>
</div>
}
我很好奇..你甚至嘗試打字Html.Check ...? –
是的,但我不知道如何將它們與我的視圖模型連接... – Maddhacker24