簡體   English   中英

MVC4:Html.DropDownList不能將值保存到模型實體嗎?

[英]MVC4: Html.DropDownList not saving value to Model Entity?

我已經在MVC4應用程序中創建了一個用於創建用戶的View 在此視圖中,用戶可以為OrganizationSponsor設置屬性,但不能同時為兩者設置。 我當前的代碼根據根據Switch選擇顯示的內容正確顯示所有組織/贊助者,但是當我在任一DropDownList進行選擇並保存新用戶時,所有DropDownLists返回的都是該UserNull值。

用戶模型(部分):

    [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):

//
        // 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發布):

    [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上,並將設置下拉列表,並且下拉值將通過帖子傳遞回控制器)

編輯

我建議您通過模型傳遞下拉列表。 添加到模型中

public SelectList OrganizationList { get; set; }
public SelectList SponsorList { get; set; }

然后在您的控制器上(在get中)

newUser.OranizationList = new SelectList(db.MemberOrganizations, "Id", "Name");
newUser.SponsorList = new SelectList(db.SponsorOrganizations, "Id", "Name");

然后在你看來

@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

@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" })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM