2

我正在构建一个 MVC 应用程序,用户可以在其中使用大量过滤器来获得他想要的东西。

以下是基于控制器方法的这些过滤器的概述:

//
// GET: /Card/SearchIndex
public ActionResult SearchIndex(string objName, string objType, string objCostSymbol, string objCost, string powerSymbol,
                                        string powerValue, string ratingSymbol, string ratingValue, string ownerName, string objSet, 
                                        string objRarity, string addCostValue, int? objNumber,
                                        string addCostValue2, string addCostValue3, string addCostValue4, string addCostValue5, string addCostValue6,
                                        bool? blueColor, bool? redColor, bool? yellowColor, bool? purpleColor, bool? greyColor, bool? blackColor,
                                        bool? musicColor, bool? allColor)
        {
             // MORE CODE HERE...
        }

我想知道如何处理所有这些过滤器的最佳方法,以及如何根据给定的参数获取 objInfo 列表。请记住,某些值可能为空。到目前为止,我所做的只是加载“所有”我可以的 objInfo,然后通过删除不需要的项目对它们进行排序,这在我的意义上是“不聪明的”,但我是 MVC 应用程序的新手,我我试图找到一种更好的方法来做到这一点。

编辑

这是生成数据的视图:

@using System.Web.Mvc.Html
@model PagedList.IPagedList<MvcApp.Models.ObjInfo>

@{
    ViewBag.Title = "SearchIndex";
}

<h2>Objects Management</h2>

<p>
    @Html.ActionLink("Create New Obj", "Create")
    @using (Html.BeginForm()){
        <p>
            <label>
                Obj Colors : Check a box to search for a color.
            </label>
            All: @Html.CheckBox("allColor", true)<br/>
            Blue: @Html.CheckBox("blueColor", true)
            Red: @Html.CheckBox("redColor", true)
            Yellow: @Html.CheckBox("yellowColor", true) <br/>
            Purple: @Html.CheckBox("purpleColor", true)
            Grey: @Html.CheckBox("greyColor", true)
            Black: @Html.CheckBox("blackColor", true)
            Music: @Html.CheckBox("musicColor", true)
        </p>
        <p>
            <label>
                Obj Values: Select a value in the list below.
            </label>
            Obj Number: <input type="number" min="0" max="9999" name="cardNumber" value="int" style="width: 70px"/><br/>
            Additional Cost (contains): @Html.DropDownList("addCost", String.Empty) + @Html.DropDownList("addCost2", String.Empty)
            + @Html.DropDownList("addCost3", String.Empty) + @Html.DropDownList("addCost4", String.Empty)
            + @Html.DropDownList("addCost5", String.Empty) + @Html.DropDownList("addCost6", String.Empty)  <br/>
            Cost: @Html.DropDownList("objCostSymbol", "=") @Html.DropDownList("objCost", String.Empty)<br />
            Power: @Html.DropDownList("powerSymbol", "=") @Html.DropDownList("powerValue", String.Empty)<br/>
            Rating: @Html.DropDownList("ratingSymbol", "=") @Html.DropDownList("ratingValue", String.Empty)<br />
            <label>
                Obj Text: Write a name, part of a name, or a word.
            </label>
            Obj Name: @Html.TextBox("objName") <br/>
            Owner: @Html.TextBox("ownerName") <br />
            <label>
                Obj Categories: Select a category in the list below.
            </label>
            Type: @Html.DropDownList("objType","All") <br/>
            Obj Set: @Html.DropDownList("objSet", "All") <br/>
            Rarity: @Html.DropDownList("objRarity", "All")<br />
            <div class="float-right">
                <input type="submit" value="Filter" name="submitbutton">
            </div>
        </p>
    }
</p>
<span style="color:red; font-size: 1.7em; font-style: italic;">@ViewData["ErrorMessage"]</span>
<table>
    <tr>
        <th>Obj Name</th>
        <th>Obj Number</th>
        <th>Obj Color</th>
        <th>Additional Cost</th>
        <th>Cost</th>
        <th>Obj Type</th>
        <th>@Html.ActionLink("Power", "SearchIndex", new {sortOrder=ViewBag.PowerSortParm})</th>
        <th>@Html.ActionLink("Rating", "SearchIndex", new {sortOrder=ViewBag.RatingSortParm})</th>
        <th>Rarity</th>
        <th>Obj Set Name</th>
        <th>Owner Name</th>
        <th></th>
    </tr>

    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.m_ObjName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.m_ObjNumber)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.m_ObjColor)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.m_ObjAddCost)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.m_ObjCost)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.m_ObjType)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.m_ObjPower)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.m_ObjRating)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.m_ObjRarity)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.m_ObjSet.m_ObjSetName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.m_ObjOwner)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.m_ObjID }) |
                @Html.ActionLink("Details", "Details", new { id=item.m_ObjID }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.m_ObjID })
            </td>
        </tr>
    }
</table>

<div>
    Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
    of @Model.PageCount

    @if (Model.HasPreviousPage)
    {
        @Html.ActionLink("<<", "SearchIndex", new {page = 1, sortOrder = ViewBag.CurrentSort})
        @Html.Raw(" ")
        @Html.ActionLink("< Prev", "SearchIndex", new {page = Model.PageNumber - 1, sortOrder = ViewBag.CurrentSort})
    }
    else
    {
        @:<<
        @Html.Raw(" ");
        @:< Prev
    }

    @if (Model.HasNextPage)
    {
        @Html.ActionLink("Next >", "SearchIndex", new {page = Model.PageNumber + 1, sortOrder = ViewBag.CurrentSort})
        @Html.Raw(" ")
        @Html.ActionLink(">>", "SearchIndex", new {page = Model.PageCount, sortOrder = ViewBag.CurrentSort})
    }
    else
    {
        @:Next >
        @Html.Raw(" ")
        @:>>
    }
</div>

任何建议都会帮助我做得更好,谢谢。

4

3 回答 3

1

Ho do you normally face this in JavaScript ? You would create an option object, like

var op = {
   cardName : "..",
   cardType : "" ,
    ...
}

and pass it to a function. Correct ?

The same do in C# too. Define a, say, Conditions class, like

public class Conditions {
    public string CardName {get;set;}
    public string CardType {get;set;}
    .. 
}

and pass it to your function, which controls the values of the properties of that type to act accordingly after.

于 2013-04-16T20:19:03.783 回答
1

你为什么不使用ModelBinder. 我认为这对您的情况非常有用。请看下面:

_ 我有一个Model

public class Employee
{
   public string Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public DateTime BirthDate { get; set; }
   public Address HomeAddress { get; set; }
}

和:ModelBinder_Employee

public class EmployeeBinder : IModelBinder {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
            var emp = new Employee {
                                       Id = controllerContext.HttpContext.Request.Form["Id"],
                                       FirstName = controllerContext.HttpContext.Request.Form["FirstName"],
                                       LastName = controllerContext.HttpContext.Request.Form["LastName"],
                                       BirthDate = new DateTime(int.Parse(controllerContext.HttpContext.Request.Form["year"]),
                                           int.Parse(controllerContext.HttpContext.Request.Form["month"]),
                                           int.Parse(controllerContext.HttpContext.Request.Form["day"]))
                                   };

            return emp;
        }
    }

然后Controller

public ActionResult Example(Employee emp) {
            return View(emp);
}

网址:http://localhost:1034/Home/Example?Id=1&LastName=lazycatit

于 2013-04-17T07:10:39.410 回答
0

这是您处理问题的一种方法。

首先,使用您的搜索参数创建一个 ViewModel。

public class FilterViewModel
{
    public string ObjName { get; set; }
    public string ObjType { get; set; }
    public string OtherType { get; set; }
}

在您的控制器中,将其传递给视图。

public virtual ActionResult SearchResults()
{
    return View(new FilterViewModel());
}

在您的 SearchResults.cshtml 中,您需要将模型编码为 json,然后使用 ajax 调用来过滤您的结果。假设有一个带有 btnFilterResults id 的按钮。这将使用 ajax 从部分视图(应该是您的表)加载结果。

<script type="text/javascript">
     var dataViewModel = @Html.Raw(Json.Encode(Model));

    $("#btnFilterResults").click(function () {
        dataViewModel.ObjName = $("#objName").val(); //Make sure the ids corresponde to your html. 
        dataViewModel.ObjType = $("#objType").val();
        dataViewModel.OtherType = $("#otherType").val();

        $.ajax({
           url: "@Url.Action(MVC.ControllerName.GetSearchResults())",
           data: { viewModel: JSON.stringify(dataViewModel) },
           success: function(data) {
               $("#tableDiv").empty(); //
               $("#tableDiv").html(data);
           }
        });
    });
</script>

最后,在您的控制器中,您可以获得结果:

[HttpGet]
public virtual ActionResult LoadTableReporteGeneral(string viewModel)
{
    var filterOptions = JsonConvert.DeserializeObject<FilterViewModel>(viewModel);
    var query = from t in db.YourTableName
                select t;
     //This returns an IQueryable with all of your data, no filtering yet.

     //Start filtering.
     if(!String.IsNullOrEmpty(filterOptions.ObjName))
     {
         query = query.Where(x => x.ObjName == filterOptions.ObjName);
     }  
     if(!String.IsNullOrEmpty(filterOptions.ObjType ))
     {
         query = query.Where(x => x.ObjType == filterOptions.ObjType );
     }  
     //and so on. 
     //Finally return a partial view with your table. 
     return PartialView(MVC.Shared.Views._YourTableName, query);
}

注意:我使用的是 T4MVC 和 Json.Net 包。

希望这可以帮助。

于 2013-04-16T22:08:40.463 回答