通过viewbag将javascript类传递给cotroller

时间:2015-07-13 08:08:53

标签: c# asp.net-mvc asp.net-mvc-4

我有一个计算页码的Index方法。因此,如果用户选择页码上的行(例如页码3)并编辑该项目,并返回索引页面 - 仍然在编号3上选择页码,这很好。但是仍应在“索引”页面中选择该行。我这样想:

控制器:

 object selection = ModelHelper.GetSelectedModelId("SubmittedForms");
            if (selection != null) {              
                IEnumerable<IEnumerable<SubmittedForm>> pp = entities.Partition(pageSize);
                int calculatedPage = 0;
                bool found = false;
                foreach (var item in pp) {
                    calculatedPage++;
                    IEnumerable<SubmittedForm> inner = item as IEnumerable<SubmittedForm>;
                    foreach (var submittedForms in inner) {
                        if (submittedForms.Id == (int)selection) {
                            found = true;
                            ViewBag.selectedRow = submittedForms.Id == (int)(ModelHelper.GetSelectedModelId("SubmittedForms") ?? 0) ? "sfs-selected sfs-selectable" : String.Empty;  

                            break;
                        }
                    }
                    if (found)
                        break;
                }
                if (found)
                pageNumber = calculatedPage;

                //SubmittedForm submittedForm;

            }

使用Javascript:

 var $row = $("tr.sfs-selected").each(function () {
            selectRow($(this), $(this).hasClass("sfs-selected"));
            });




    })

并查看:

@foreach (var item in Model) {
                <tr class="(@ViewBag.selectedRow)">
                    <td>
                        @Html.DisplayFor(modelItem => item.Id)
                    </td>
                    <td>
                        @if (item.ProductId != null) {
                            @item.Product.Name

                            if (item.Product.IsProduction == false) {
                                <em>(@Resources.Entity.Environment.Test)</em>
                            }

                            if (testMode != item.Product.IsProduction) {
                                <a href="@Url.Action("Details", "Product", new { id = item.ProductId })"><i class="fa fa-fw fa-external-link-square text-info"></i></a>
                            }
                        }

但是在返回索引页面后没有选择该行。

谢谢

完整的索引方法:

[Route("sort/{SortColumn}/{SortOrder?}", Name = "Sort-SubmittedForms")]
        [Route("page/{Page:int}/{SortColumn}/{SortOrder?}", Name = "Paging-SubmittedForms")]
        [Route("search/{SearchString}")]
        [Route()]
        public ActionResult Index(string searchString, string filter, string currentFilter, string sortColumn, string sortOrder, int? page, int? id)
        {
            IOrderedQueryable<SubmittedForm> entities = db.FilteredSubmittedForms;



            if (searchString != null) page = 1; else searchString = currentFilter;
            //if (page == null && Session["SubmittedFormpage"] != null)
            //    page = (int)Session["SubmittedFormpage"];

            bool isHandler = ApplicationUserManager.IsProductHandler(this.User);

            bool hideArchivedOrders = true;

            if (filter != null) {
                int productId = 0;
                string stateFilter = null;
                if (filter.StartsWith("o_")) {  // Order state
                    if (isHandler)
                        filter = null;
                    else {
                        stateFilter = filter.Substring(2);
                        OrderState oState = db.OrderStates.FirstOrDefault(s => s.Code == stateFilter);
                        if (oState == null)
                            filter = null;
                        else {
                            entities = (IOrderedQueryable<SubmittedForm>)entities.Where(
                                        s => s.Order.OrderState.Code == stateFilter
                                );
                            AddFixedNotification(String.Format(Resources.Entity.Environment.FitleredByOrderStateMessage, oState.Title));
                            hideArchivedOrders = false;
                        }
                    }
                }
                else if (filter.StartsWith("s_")) { // Submitted form state
                    stateFilter = filter.Substring(2);
                    SubmittedFormStateEnum sfState;
                    if (SubmittedFormState.TryCodeToId(stateFilter, out sfState)) {
                        entities = (IOrderedQueryable<SubmittedForm>)entities.Where(
                                    s => s.SubmittedFormStateId == (int) sfState
                                        && s.Order.OrderState.Code == OrderState.CompletedCode
                            );
                        AddFixedNotification(String.Format(Resources.Entity.Environment.FilteredBySubmittedFormStateMessage, SubmittedFormState.IdToLocalizedName(sfState)));
                    }
                    else {
                        filter = null;
                    }
                }
                else if (int.TryParse(filter, out productId) && productId > 0) {
                    Product product = db.Products.Find(productId);
                    if (product == null) productId = 0;
                    else {
                        entities = (IOrderedQueryable<SubmittedForm>)entities.Where(
                                s => s.Product.Id == productId
                        );
                        AddFixedNotification(String.Format(Resources.Entity.Environment.FilteredByProductMessage, product.Name));
                    }
                    filter = productId.ToString();
                }
                else
                    filter = null;
            }

            if (isHandler) {
                entities = FilterSubmittedFormsForProductHandler(entities);
            }
            else if (hideArchivedOrders) {
                entities = (IOrderedQueryable<SubmittedForm>)entities.Where(
                                    s => s.Order.OrderState.Code != OrderState.ArchivedCode
                            );
            }

            if (!String.IsNullOrEmpty(searchString)) {
                entities = (IOrderedQueryable<SubmittedForm>)entities.Where(
                        s => s.Product.Name.ToUpper().Contains(searchString.ToUpper())
                );
                AddFixedNotification(String.Format(Resources.Entity.Environment.FilteredBySearchTermMessage, searchString));
            }

            switch (sortColumn) {
                case "id":
                    entities = (sortOrder == "desc") ? entities.OrderByDescending(s => s.Id) : entities.OrderBy(s => s.Id);
                    break;
                case "product":
                    entities = (sortOrder == "desc") ? entities.OrderByDescending(s => s.Product.Name) : entities.OrderBy(s => s.Product.Name);
                    break;
                case "modified":
                    entities = (sortOrder == "desc") ? entities.OrderByDescending(s => s.ModificationDate) : entities.OrderBy(s => s.ModificationDate);
                    break;
                case "attach":
                    entities = (sortOrder == "desc") ? entities.OrderByDescending(s => s.SubmittedFormAttachments.Count) : entities.OrderBy(s => s.SubmittedFormAttachments.Count);
                    break;
                case "orderstate":
                    entities = (sortOrder == "desc") ? entities.OrderByDescending(s => s.Order.OrderStateId) : entities.OrderBy(s => s.Order.OrderStateId);
                    break;
                default:
                    sortColumn = "id";
                    sortOrder = "desc";
                    entities = (sortOrder == "desc") ? entities.OrderByDescending(s => s.Id) : entities.OrderBy(s => s.Id);
                    break;
            }

            ViewBag.SortColumn = sortColumn;
            ViewBag.SortOrder = sortOrder == "desc" ? "desc" : "";
            ViewBag.SearchString = searchString;
            ViewBag.Filter= filter;
            //Session["SubmittedFormpage"] = page;



            if (isHandler)
                ViewBag.OrderStates = new Dictionary<string, string>();
            else
                ViewBag.OrderStates = db.OrderStates.ToDictionary(s => s.Code, s => s.Title);

            bool production = !StateHelper.IsTestMode();
            ViewBag.ProductsInUse = db.Products.Where(p => p.SubmittedForms.Where(f => f.Order.IsProduction == production).Count() != 0)
                .OrderBy(p => p.Name)
                .ToDictionary(p => p.Id.ToString(), p => p.Name + " (" + p.SubmittedForms.Where(f => f.Order.IsProduction == production).Count() + ")");

            int pageSize = StateHelper.GetPageSize();
            int pageNumber = StateHelper.HasPageSizeChanged ? 1 : (page ?? 1);

            object selection = ModelHelper.GetSelectedModelId("SubmittedForms");
            if (selection != null) {              
                IEnumerable<IEnumerable<SubmittedForm>> pp = entities.Partition(pageSize);
                int calculatedPage = 0;
                bool found = false;
                foreach (var item in pp) {
                    calculatedPage++;
                    IEnumerable<SubmittedForm> inner = item as IEnumerable<SubmittedForm>;
                    foreach (var submittedForms in inner) {
                        if (submittedForms.Id == (int)selection) {
                            found = true;
                            ViewBag.selectedRow = submittedForms.Id == (int)(ModelHelper.GetSelectedModelId("SubmittedForms") ?? 0) ? "sfs-selected sfs-selectable" : String.Empty;  

                            break;
                        }
                    }
                    if (found)
                        break;
                }
                if (found)
                pageNumber = calculatedPage;

                //SubmittedForm submittedForm;

            }

            //ModelHelper.GetSelectedModelId("SubmittedForms");
            //SubmittedForm submittedform = db.SubmittedForms.Find(id);

            return View(entities.ToPagedList(pageNumber, pageSize));
        }

这是两个辅助方法:

 public static object GetSelectedModelId(string ControllerName)
        {
            //var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;
            string controller = (string)HttpContext.Current.Session["controller"];
            object mid = null;


            if (controller != null && controller.Equals(ControllerName, StringComparison.OrdinalIgnoreCase)) 
             mid =   HttpContext.Current.Session["SelectedModelId"];            
            HttpContext.Current.Session.Remove("SelectedModelId");
            HttpContext.Current.Session.Remove("controller");

            return mid;
        }

        public static void SetSelectedModelId(string ControllerName, object ModelId)
        {
            HttpContext.Current.Session["controller"] = ControllerName;
            HttpContext.Current.Session["SelectedModelId"] = ModelId;
        }

1 个答案:

答案 0 :(得分:0)

下面的课程将包括括号,这是否打算,因为你的javascript不包含它?

getUserById(userId:Long):Option[User]