MVC4: Html.下拉列表没有将值保存到模型实体
本文关键字:保存 模型 实体 Html 下拉列表 MVC4 | 更新日期: 2023-09-27 18:02:09
我在我的MVC4应用程序中创建了一个View
用于创建用户。在此视图中,用户可以为Organization
或Sponsor
设置属性,但不能同时设置两者。我当前的代码正确地显示了所有的组织/赞助商,这取决于基于Switch选择显示的内容,但是当我在DropDownList
中进行选择并保存新用户时,所有的下拉列表返回的是User
的Null
值。
Users Model (Partial):
[GridColumn(Title = "Org.", SortEnabled = true, Width = "100")]
public int? MemberOrgId { get; set; }
[NotMappedColumn]
public int? SponsorOrgId { get; set; }
[ForeignKey("MemberOrgId")]
[NotMappedColumn]
public virtual MemberOrganizations Organization { get; set; }
[ForeignKey("SponsorOrgId")]
[NotMappedColumn]
public virtual SponsorOrganizations Sponsor { get; set; }
创建(视图):
@model PROJECT.Models.Users
@{
ViewBag.Title = "Create";
Layout = "~/Areas/Admin/.../.../.../_AdminLayout.cshtml";
string cancelEditUrl = "/Admin/UserController/";
}
@using (Html.BeginForm("Create", "UserController", FormMethod.Post, new { enctype = "multipart/form-data" })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.RegisteredDate)
<div class="container">
<div class="row">
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field" style="margin-bottom: 15px">
@Html.TextBoxFor(model => model.Email, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Email)
</div>
</div>
<input type="checkbox" value="12345" name="Sponsor-Organization" checked class="userCreate-BSSwitch"/>
<div style="margin-bottom: 15px">
<div class="row switchOn">
<div class="editor-label">
@Html.LabelFor(model => model.MemberOrgId, "Organization")
</div>
<div class="editor-field">
@Html.DropDownList("OrganizationId", null, String.Empty, new { @class = "form-control", @id = "OrgIdDropDown" })
@Html.ValidationMessageFor(model => model.MemberOrgId)
</div>
</div>
<div class="row switchOff">
<dliv class="editor-label">
@Html.LabelFor(model => model.SponsorOrgId, "Sponsor")
</dliv>
<div class="editor-field" >
@Html.DropDownList("SponsorId", null, String.Empty, new { @class = "form-control", @id = "SponsorIdDropDown" })
@Html.ValidationMessageFor(model => model.SponsorOrgId)
</div>
</div>
</div>
<div class="row" id="submitRow">
<div class="btn-group ">
<button type="submit" value="Save" class="btn btn-success">Create User</button>
</div>
<a href="@cancelEditUrl" onclick="confirmCancel()" class="btn btn-danger">Cancel</a>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
<script type="text/javascript">
jQuery(document).ready(function () {
setTimeout(function () { $("#alert").alert('close'); }, 5000);
$('.switchOff').addClass('hide');
});
$.fn.bootstrapSwitch.defaults.onText = 'Member';
$.fn.bootstrapSwitch.defaults.offText = 'Sponsor';
$.fn.bootstrapSwitch.defaults.offColor = 'info';
$.fn.bootstrapSwitch.defaults.animate = false;
//$.fn.bootstrapSwitch.defaults.size = 'large';
$(document).ready(function () {
$('input:checkbox[name="Sponsor-Organization"]').bootstrapSwitch();
});
$('input:checkbox[name="Sponsor-Organization"]').on('switchChange.bootstrapSwitch', function (event, state) {
var checked = state;
if (checked) {
$('.switchOn').removeClass('hide');
$('.switchOff').addClass('hide');
$('#SponsorIdDropDown').val("");
}
else {
$('.switchOff').removeClass('hide');
$('.switchOn').addClass('hide');
$('#OrgIdDropDown').val("");
}
});
$(document).ready(function () {
$(".btn-danger").click(function () {
var cancel = confirm("Are you sure? Entered data will be lost.")
if (cancel != true) {
event.preventDefault(); // cancel the event
}
});
});
//$('input:checkbox[name="Sponsor-Organization"]').on('switchChange.bootstrapSwitch', function(event, state) {
</script>
Controller (Create GET):
//
// GET: /Admin/
public ActionResult Create()
{
ViewBag.headerTitle = "Create a User";
ViewBag.OrganizationId = new SelectList(db.MemberOrganizations, "Id", "Name");
ViewBag.SponsorId = new SelectList(db.SponsorOrganizations, "Id", "Name");
Users newUser = new Users();
newUser.RegisteredDate = DateTime.Now;
newUser.LastVisitDate = DateTime.Now;
newUser.ProfilePictureSrc = null;
return View(newUser);
}
控制器(创建http - post):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Users users)
{
ViewBag.headerTitle = "Create a User";
if (ModelState.IsValid)
{
WebSecurity.CreateUserAndAccount(users.Email, "defaultPassword");
Users user2 = db.Users.Where(u => u.Email == users.Email).FirstOrDefault();
user2.Enabled = true;
user2.Password = Membership.GeneratePassword(15, 7);
user2.ForumUsername = users.Name;
user2.RegisteredDate = DateTime.Now;
user2.ReceiveSystemEmails = true;
db.Entry(user2).State = EntityState.Modified;
db.SaveChanges();
string[] roleNames = new string[] { "role1", "role2", "role3" };
System.Web.Security.Roles.AddUserToRoles(users.Email, roleNames);
return RedirectToAction("Index");
}
}
有人对这件事有什么看法吗?我尝试了在其他问题中找到的一些不同的建议,但到目前为止还没有任何效果。这是我的第一个MVC应用,所以我觉得我可能忽略了一些非常基本的东西。
对于绑定到模型的字段,它必须在"for" helper中(除了display)。试着像这样改变下拉菜单
@Html.DropDownListFor(x => x.OrganizationId, null, String.Empty, new { @class = "form-control"})
@Html.DropDownListFor(x => x.SponsorId, null, String.Empty, new { @class = "form-control" })
假设您的用户模型有字段OrganizationId和SponsorId,这些字段将被绑定到下拉列表(在get上设置它们,下拉列表将被设置,下拉列表的值将通过post传递回控制器)
编辑
我建议将你的下拉列表传递给你的模型。给你的模型添加public SelectList OrganizationList { get; set; }
public SelectList SponsorList { get; set; }
then on your controller (in the get)
newUser.OranizationList = new SelectList(db.MemberOrganizations, "Id", "Name");
newUser.SponsorList = new SelectList(db.SponsorOrganizations, "Id", "Name");
then on your view
@Html.DropDownListFor(x => x.MemberOrgId, Model.OrganizationList, new { @class = "form-control" })
public class MyModel
{
public MyModel()
{
this.myDDLList = new List<SelectListItem>();
}
public List<SelectListItem> myDDLList { get; set; }
public int ddlID { get; set; }
}
public ActionResult Index()
{
MyModel model = new MyModel();
using (YourEntities context = new YourEntities())
{
var list = context.YourTable.ToList();
foreach (var item in list)
{
model.myDDLList.Add(new SelectListItem() { Text = item.NameField, Value = item.ValueField.ToString() });
}
}
return View(model);
}
@Html.DropDownListFor(x => x.ddlID, Model.myDDLList)
我通过使用ViewData[]
将预填充的选择列表从控制器传递到我的视图来解决这个问题:
// GET: /Admin/
public ActionResult Create()
{
ViewBag.headerTitle = "Create a User";
ViewData["Organization"] = new SelectList(db.MemberOrganizations, "Id", "Name");
ViewData["Sponsor"] = new SelectList(db.SponsorOrganizations, "Id", "Name");
Users newUser = new Users();
newUser.RegisteredDate = DateTime.Now;
newUser.LastVisitDate = DateTime.Now;
newUser.ProfilePictureSrc = null;
return View(newUser);
}
,然后在我看来,只是在ViewData[]
的值读取到我的Html.DropDownList
的单独SelectList
's:
@Html.DropDownList("MemberOrgId", ViewData["Organization"] as SelectList, String.Empty, new { @class = "form-control", @id = "MemberOrgId" })
@Html.DropDownList("SponsorOrgId", ViewData["Sponsor"] as SelectList, String.Empty, new { @class = "form-control", @id = "SponsorOrgId" })