C# MVC4:Html.DropDownList是否未将值保存到模型实体?
我在MVC4应用程序中创建了一个C# MVC4:Html.DropDownList是否未将值保存到模型实体?,c#,asp.net-mvc,asp.net-mvc-4,twitter-bootstrap-3,html.dropdownlistfor,C#,Asp.net Mvc,Asp.net Mvc 4,Twitter Bootstrap 3,Html.dropdownlistfor,我在MVC4应用程序中创建了一个视图,用于创建用户。在此视图中,用户可以为组织或赞助商设置属性,但不能同时为两者设置属性。我的当前代码根据开关选择显示的内容正确显示所有组织/赞助商,但当我在DropDownList中进行选择并保存新用户时,所有DropDownLists返回的Null值都是用户的值 用户模型(部分): [GridColumn(Title = "Org.", SortEnabled = true, Width = "100")] public int? Member
视图
,用于创建用户。在此视图中,用户可以为组织
或赞助商
设置属性,但不能同时为两者设置属性。我的当前代码根据开关选择显示的内容正确显示所有组织/赞助商,但当我在DropDownList
中进行选择并保存新用户时,所有DropDownLists返回的Null
值都是用户的值
用户模型(部分):
[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>
//
// 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);
}
[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");
}
}
创建(视图):
[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>
//
// 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);
}
[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");
}
}
控制器(创建HTTP Post):
[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>
//
// 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);
}
[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”助手中(显示除外)。尝试像这样更改下拉列表
@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; }
然后在控制器上(在get中)
那么在你看来
@Html.DropDownListFor(x => x.MemberOrgId, Model.OrganizationList, new { @class = "form-control" })
公共类MyModel
{
公共MyModel()
{
this.myDDLList=新列表();
}
公共列表myDDLList{get;set;}
公共int ddlID{get;set;}
}
公共行动结果索引()
{
MyModel model=新的MyModel();
使用(YourEntities上下文=新建YourEntities())
{
var list=context.YourTable.ToList();
foreach(列表中的变量项)
{
model.myDDLList.Add(新的SelectListItem(){Text=item.NameField,Value=item.ValueField.ToString()});
}
}
返回视图(模型);
}
@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
:
@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" })
当您说“所有DropDownLists返回的对于用户是空值”时,您的意思是控制器中的用户的属性是空的?您的模型中是否有名为OrganizationId和SponsorId的属性?因为这是视图中绑定下拉列表选择的地方。当我的控制器Create()方法的HTTP Post完成时,如果我在下拉列表中选择了一个值,则会创建用户,但相应的字段仍然指定为NULL
。我忘了在我的模型中将OrganizationId
更改为MemberOrgID
,SponsorId
更改为sponsorgid
。我原以为将@Html.DropDownList()
更改为引用那些可以修复它,但现在我收到:@Html.DropDownList(“MemberOrgId”,null,String.Empty,new{@class=“form control”,@id=“OrgIdDropDown”})
-没有类型为“IEnumerable”的ViewData项具有键“MemberOrgId”
我在上面列出了相关的用户
模型字段。我尝试了@Html.DropDownListFor(x=>x.MemberOrgId,null,string.Empty,new{@class=“form control”,@id=“OrgIdDropDown”})
,但我的视图无法加载:,没有“IEnumerable”类型的ViewData项具有“MemberOrgId”键。
?我添加了一个关于如何通过模型而不是视图数据/包传递下拉列表的编辑。尝试新代码我不确定如何在MVC中查询数据库中的列表?我在控制器中为我的Create()添加了GET。我更改了编辑以使用您的代码。由于您有2个下拉列表,因此您的模型中应该有2个“选定”字段。在我的示例中,下拉列表的选定值将传回MemberOrgId字段中的控制器。我不知道这是否是您希望所选值进入的字段,也不确定您希望另一个下拉列表进入的字段。为了安全起见,我清除了数据库和迁移,并执行了新的InitialCreate。我更新了数据库,然后添加了您在编辑中指定的所有内容。但是,当我现在尝试运行时,我在HomeController上遇到一个内部异常:从第6行开始映射片段时出现问题:没有为Set Users中的properties Users.OrganizationList、Users.SponsorList指定映射。\r\n当:\r\n Entity为type[PROJECT.DAL.Users]
时,具有键(PK)的实体将不会往返?