MVC 3 RAZOR - 如何使用隐藏字段来维护页面请求之间的复选框状态?

时间:2012-11-16 16:00:37

标签: asp.net-mvc-3 razor checkbox hidden-field

我正在使用隐藏字段来维护页面请求之间的复选框状态,除非它不起作用。因此,当我点击我的webgrid转到接下来的15条记录时,它会忘记检查哪些复选框。

索引视图

@model IEnumerable<UserManager.Models.vw_UserManager_Model>
@{
    ViewBag.Title = "User Manager Dashboard";
}
@Html.ActionLink("Create New User", "CreateUser")
@using (@Html.BeginForm())
{
    <div class="webgrid-filter">
        @{Html.RenderAction("_WebGridFilter", "UserManager");}
    </div>

    <div id="webgrid-wrapper">
        @Html.Partial("~/Views/Partial/_WebGridUserManager.cshtml", Model)
    </div>
    <br />
}
<script type="text/javascript">
    $(document).ready(function () {

        // Disable checkboxs where a user is not active.
        $(".webgrid-wrapper input:not(:checked)").attr("disabled", "disabled");

        // Style tables.
        function jQueryUIStyling() {
            $('input:button, input:submit').button();

            $('.webgrid-wrapper').addClass('ui-grid ui-widget ui-widget-content ui-corner-all');
            $('.webgrid-title').addClass('ui-grid-header ui-widget-header ui-corner-top');
            jQueryTableStyling();
        } // end of jQueryUIStyling

        function jQueryTableStyling() {
            $('.webgrid').addClass('ui-grid-content ui-widget-content');
            $('.webgrid-header').addClass('ui-state-default');
            $('.webgrid-footer').addClass('ui-grid-footer ui-widget-header ui-corner-bottom ui-helper-clearfix');
        } // end of jQueryTableStyling
    });
</script>
<script type="text/javascript">

    function filterGrid() {
        var filters = getFilterVals();
        $.ajax({
            url: '@Url.Action("Index", "UserManager")',
            type: "POST",
            async: true,
            dataType: "html",
            data: "alfConnect=" + filters.alfConnect + "&" + "alfIntelligence=" + filters.alfIntelligence + "&" + "brad=" + filters.brad,
            success: function (data) {
                $('#webgrid-wrapper').empty().html(data);
                //                $('#webgrid-wrapper').html(data);
            }
        });
    }

    function getFilterVals() {
        filters = new Object();
        if ($('.webgrid-filter #chkFilterAlfIntell').is(':checked')) {
            filters.alfIntelligence = 1;
        }
        else {
            filters.alfIntelligence = 0;
        }

        if ($('.webgrid-filter #chkFilterAlfConn').is(':checked')) {
            filters.alfConnect = 1;
        }
        else {
            filters.alfConnect = 0;
        }

        if ($('.webgrid-filter #chkFilterBrad').is(':checked')) {
            filters.brad = 1;
        }
        else {
            filters.brad = 0;
        }
        return filters;

    }

    function logUserOff(url) {
        var answer = confirm('Are you sure you want to save this data?')
        if (answer) {
            //            alert(url + ": " + value);

            $.ajax({
                url: url,
                type: "POST"
                //                data: value
            }).done(function () {
                $(this).addClass("done");
            });


            return true;
        }
        else {
            return false;
        }
    };
</script>

隐藏字段的部分视图

@model UserManager.Models.webgrid_validation
<b>@Html.Label("Select a filter: ")</b>
<br />

@Html.Label("Toggle ALF Intelligence users:")
@Html.CheckBoxFor(model => model.chkBoxAlfIntelligence, new
{
    id = "chkFilterAlfIntell",
    onclick = "filterGrid()",
    @checked = "checked"

})
@Html.Hidden("hdnAlfIntelligence", Model.chkBoxAlfIntelligence)

@Html.Label("Toggle ALF Connect users:")
@Html.CheckBoxFor(model => model.chkBoxAlfConnect, new
{
    id = "chkFilterAlfConn",
    onclick = "filterGrid()",
    @checked = "checked"
})
@Html.Hidden("hdnAlfConnect", Model.chkBoxAlfConnect)

@Html.Label("Toggle BRAD users:")
@Html.CheckBoxFor(model => model.chkBoxBrad, new
{
    id = "chkFilterBrad",
    onclick = "filterGrid()",
    @checked = "checked"

})
@Html.Hidden("hdnBrad", Model.chkBoxBrad)

控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UserManager.Models;

namespace UserManager.Controllers
{
    public class UserManagerController : Controller
    {
        //
        // GET: /UserManager/

        public ActionResult Index()
        {
            try
            {
                var model = new UserManagerTestEntities().vw_UserManager_Model;
                return View(model.ToList());

            }
            catch (Exception ex)
            {
                return View(ViewBag);
            }

        }

        [HttpPost]
        public ActionResult Index(int alfConnect, int alfIntelligence, int brad)
        {
            List<UserManager.Models.vw_UserManager_Model> modelList = DAL.getGrid(alfConnect, alfIntelligence, brad);


                        switch (alfConnect)
            {
                case 1:
                    ViewData["chkBoxAlfConnect"] = 1;
                    break;
                case 0:
                    ViewData["chkBoxAlfConnect"] = 0;
                    break;
            }

            switch (alfIntelligence)
            {
                case 1:
                    ViewData["chkBoxAlfIntelligence"] = 1;
                    break;
                case 0:
                    ViewData["chkBoxAlfIntelligence"] = 0;
                    break;
            }

            switch (brad)
            {
                case 1:
                    ViewData["chkBoxBrad"] = 1;
                    break;
                case 0:
                    ViewData["chkBoxBrad"] = 0;
                    break;
            }

            return PartialView("~/Views/Partial/_WebGridUserManager.cshtml", modelList);  
        }

        [ChildActionOnly]
        public ActionResult _WebGridFilter ()
        {
            UserManager.Models.webgrid_validation model = new webgrid_validation();


            return PartialView("~/Views/Partial/_WebGridFilter.cshtml", model);
        }


        //public ActionResult _WebGridFilter(int alfConnect, int alfIntelligence, int brad)
        //{
        //    UserManager.Models.webgrid_validation model = new webgrid_validation();

            //switch (alfConnect)
            //{
            //    case 1:
            //        model.chkBoxAlfConnect = true;
            //        break;
            //    case 0:
            //        model.chkBoxAlfConnect = false;
            //        break;
            //}

            //switch (alfIntelligence)
            //{
            //    case 1:
            //        model.chkBoxAlfIntelligence = true;
            //        break;
            //    case 0:
            //        model.chkBoxAlfIntelligence = false;
            //        break;
            //}

            //switch (brad)
            //{
            //    case 1:
            //        model.chkBoxBrad = true;
            //        break;
            //    case 0:
            //        model.chkBoxBrad = false;
            //        break;
            //}
        //    return PartialView("~/Views/Partial/_WebGridFilter.cshtml", model);
        //}



        #region ajaxMethods
        public ActionResult LookUpGroupName(string q, int limit)
        {

            try
            {
                //TODO: Map list to autocomplete textbox control
                DAL d = new DAL();
                List<string> groups = d.groups();

                var GroupValue = groups
                    .Where(x => x.Contains(q))
                    .OrderBy(x => x)
                    .Take(limit)
                    .Select(r => new { group = r });

                // Return the result set as JSON
                return Json(GroupValue, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return View(ex.ToString());
            }
        }

        public ActionResult LogUserOff(string userid)
        {

            try
            {
                //TODO: Map list to autocomplete textbox control

                return View();

            }
            catch (Exception ex)
            {
                return View(ex.ToString());
            }
        }

        //[HttpPost]
        //public ActionResult FilterGrid(int alfConnect, int alfIntelligence, int brad)
        //{
        //    List<UserManager.Models.vw_UserManager_Model> modelList  = DAL.getGrid(alfConnect, alfIntelligence, brad);

        //    return PartialView("_WebGridUserManager", modelList);
        //}

        #endregion

        #region crud
        public ActionResult CreateUser()
        {
            //var data = new UserManager.Models.UserManagerTestEntities();
            ViewBag.Message = "Create New User";
            var model = new vw_UserManager_Model();
            return View(model);
        }

        [HttpPost]
        public ActionResult CreateUser (vw_UserManager_Model model)
        {

                int outcome = 0;
                if (ModelState.IsValid)
                {
                    //var data = new UserManager.Models.UserManagerTestEntities();
                    // Pass model to Data Layer
                     outcome = UserManager.DAL.CreateUser(model, outcome);
                    //data.SaveChanges();
                }

                if (outcome > 0) // Success
                {

                    return RedirectToAction("showSuccess", model);

                }
                else // Failure
                {
                    return RedirectToAction("showError", new { ErrorMessage = "Error" });
                }
        }

        public ActionResult EditUser(Guid userid, string salutation, string firstname, string lastname, string password, Nullable<bool> isactive,  Nullable<int> maxconcurrentusers, string email, string module, string group)
        {
            vw_UserManager_Model editUser = new vw_UserManager_Model();
            editUser.userid = userid;
            editUser.salutation = salutation;
            editUser.firstname = firstname;
            editUser.lastname = lastname;
            editUser.password = password;
            editUser.isactive = isactive;
            editUser.MaxConcurrentUsers = maxconcurrentusers;
            editUser.email = email;
            editUser.module_name = module;
            editUser.group_name = group;
            return View(editUser);
        }

        [HttpPost]
        public ActionResult EditUser(vw_UserManager_Model editUser)
        {
            if (ModelState.IsValid)
            {
                UserManager.DAL.EditUser(editUser);
            }

            return View();
        }

        public ActionResult DeleteUser(Guid userid, string username, string salutation, string firstname, string lastname, string password, bool isactive, string email, string module, string group)
        {
            vw_UserManager_Model DeleteUser = new vw_UserManager_Model();
            DeleteUser.userid = userid;
            DeleteUser.UserName = username;
            DeleteUser.salutation = salutation;
            DeleteUser.firstname = firstname;
            DeleteUser.lastname = lastname;
            DeleteUser.password = password;
            DeleteUser.isactive = isactive;
            DeleteUser.email = email;
            DeleteUser.module_name = module;
            DeleteUser.group_name = group;

            return View(DeleteUser);
        }

        [HttpPost]
        public ActionResult DeleteUser(vw_UserManager_Model deleteUser)
        {
            if (ModelState.IsValid)
            {
                UserManager.DAL.DeleteUser(deleteUser);
                return RedirectToAction("showSuccess", new { SuccessMessage = "Success" });
            }

            return View();
        }
        #endregion crud

        #region successErrorHandling
        public ActionResult showError(List<string> ErrorMessage)
        {
                ViewBag.ErrorMessage = ErrorMessage[0];
                return View("ErrorMessageView");
        }

        public ActionResult showSuccess(vw_UserManager_Model model)
        {

            return View("SuccessMessageeView", model);
        }
        #endregion
    }
}

我的问题是如何使用隐藏字段来维护页面请求之间的复选框状态?

1 个答案:

答案 0 :(得分:0)

您可以删除表单并将数据作为JSon值发送到控制器,因此只刷新需要刷新的页面部分。

此致