传递到字典中的模型项是A类型,但此字典需要类型为B

时间:2018-03-16 18:55:22

标签: c# asp.net asp.net-mvc model-view-controller

我是初学ASP.net编码器。我知道控制器正在调用List并且模型正在调用泛型模型,并且可以通过将视图中的模型设置为@model IEnumerable<WebApplication2.Models.Strategy>

来轻松修复

但我希望能够在视图中调用模型,以便在我的视图中调用它。下面我发布了我的代码。

控制器:

public ActionResult Index(string group, string prin, string status, string osr, string groupnew, string stratvar, string fltstring, Strategy selg, FormCollection form)
        {

            if (Session["UserId"] != null)
            {
                Strategy strat = new Strategy();

                int id = Int32.Parse(Session["UserId"].ToString()); // Get the user id from the session
                String em = db.UserAccounts.Find(id).Email.ToString(); // Use the id to get the associated email address
                EmailList emailListItem = db.EmailLists.First(x => x.Email == em); // Use the email address to get the associated emaillist object which holds the group

                string perm = emailListItem.Perm;

                if (perm == null)
                {
                    perm = "0";
                }
                ViewData["perm"] = perm;

                // if external
                if (!emailListItem.IntExt)
                {
                    // Create a list to hold the Todos which we will end up showing
                    List<Strategy> list = new List<Strategy>();

                    // this is a foreach loop, it goes through all the Todos returned from db.Todoes.ToList()
                    foreach (Strategy s in db.Strategies.ToList())
                    {
                        // makes sure that the group of a todo isn't null (empty)
                        if (!String.IsNullOrEmpty(s.Group))
                        {
                            // checks if the group of the user is equal to the group of the post. if so it adds the todo to the list.
                            if (emailListItem.Group.Equals(s.Group))
                            {
                                list.Add(s);
                            }
                        }
                    }

                    return View(list);

                }
                else
                {
                    // This is the query building code. 
                    string p = emailListItem.Perm;
                    string gr = emailListItem.Group;
                    StringBuilder sb = new StringBuilder();
                    sb.Append("SELECT * FROM dbo.Strategy WHERE "); //change table name for whatever you need returned
                    foreach (char c in p.ToCharArray())
                    {
                        if (group == null)
                        {
                            sb.Append("Perm LIKE '%");
                            sb.Append(c);
                            sb.Append("%' OR ");
                        }

                    }
                    sb.Length = sb.Length - 4;


                    if (selg == null)
                    {

                        List<Strategy> list = db.Strategies.SqlQuery(sb.ToString()).ToList(); //change table name
                        return View(list);
                    }

                    else
                    {

                        var groups = from g in db.Strategies
                                     select g;
                        var prins = from pr in db.Strategies
                                    select pr;
                        var osrs = from o in db.Strategies
                                   select o;
                        var statuss = from s in db.Strategies
                                      select s;


                        ViewBag.Groupcmb = (from g in db.Strategies.Include(p) where g.Group != null
                                         select g.Group).Distinct();

                        ViewBag.Principalcmb = (from pr in db.Strategies.Include(p) where pr.Principal != null
                                             select pr.Principal).Distinct();

                        ViewBag.OSRcmb = (from o in db.Strategies.Include(p) where o.OSR != null
                                          select o.OSR).Distinct();

                        ViewBag.Statuscmb = (from s in db.Strategies.Include(p) where s.Status != null
                                          select s.Status).Distinct();


                        //ViewData["OSR"] = new SelectList(ViewBag.OSRcmb);
                        ViewBag.osrsel = osr;

                        //if all filters are null
                        if (group == null && stratvar == null && prin == null && osr == null && status == null)
                        {
                            return View(db.Strategies.ToList());
                        }

                        //returns same search filter for group if edit 
                        if (stratvar != null && group == null)
                        {

                            group = stratvar;
                            groups = groups.Where(g => g.Group.Contains(group));
                            //  return View(group.ToList());
                        };



                        if (prin != null && group != null && osr != null && status != null)
                       {
                            ViewBag.osrsel = osr;
                            prins = prins.Where(gpr => gpr.Principal.Contains(prin) && gpr.Group.Contains(group) && gpr.OSR.Contains(osr) && gpr.Status.Contains(status));
                            stratvar = null;
                            return View(prins.ToList());
                        }


                        return View(strat);
                    }

                }

            }
            else
            {
                return RedirectToAction("Login", "Account");
            }

        }

查看:

 @model WebApplication2.Models.Strategy

<h2>Index</h2>

<div class="col-md-6">
    @Html.ActionLink("Create New", "Create")
</div>
<div class="col-md-6">
    @if ((ViewData["perm"]).ToString() != "0")
    {



        using (Html.BeginForm())
        {

            <table>
                <tr>
                    <td>Group</td>
                    <td>@Html.DropDownList("group", new SelectList(ViewBag.Groupcmb), "--Select--")</td>
                    <td>Status</td>
                    <td>@Html.DropDownList("status", new SelectList(ViewBag.Statuscmb), "--Select--")</td>
                    <td>Principal</td>
                    <td>@Html.DropDownList("prin", new SelectList(ViewBag.Principalcmb), "--Select--")</td>
                    <td>OSR</td>
                    <td>@Html.DropDownListFor(m => m.OSR, new SelectList(ViewBag.OSRcmb), "--Select--")</td>
                    <td>
                        <input type="submit" value="Search" onclick="location.href='@Url.Action("Index", "Strategy")'" />
                    </td>
                </tr>
            </table>


        }

    }
    else if ((ViewData["perm"]).ToString() == "0")
    {
        <div class="col-md-6 hide">

            @using (Html.BeginForm())
            {

            }
        </div>
    }

</div>
<div class="col-md-12"></div>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Customer)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Product)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Status)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.NextAction)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Updated)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FollowUpDate)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.OSR)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Principal)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Value)
        </th>
        <th></th>
    </tr>

    @*@foreach (var item in Model)
        {*@
    <tr>
        <td>
            @Html.DisplayFor(model => model.Customer)
        </td>
        <td>
            @Html.DisplayFor(model => model.Product)
        </td>
        <td>
            @Html.DisplayFor(model => model.Status)
        </td>
        <td>
            @Html.DisplayFor(model => model.NextAction)
        </td>
        <td>
            @Html.DisplayFor(model => model.Updated)
        </td>
        <td>
            @Html.DisplayFor(model => model.FollowUpDate)
        </td>
        <td>
            @Html.DisplayFor(model => model.OSR)
        </td>
        <td>
            @Html.DisplayFor(model => model.Principal)
        </td>
        <td>
            @Html.DisplayFor(model => model.Value)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = Model.StrategyId, group = Model.Group }) |
            @Html.ActionLink("Details", "Details", new { id = Model.StrategyId })
            @*|*@
         </td>
    </tr>
</table>

2 个答案:

答案 0 :(得分:0)

您可以在视图中将模型类型设置为:

@model IEnumerable<WebApplication2.Models.Strategy>

并在视图上:

if(Model != null)
{
    foreach(var strategy in Model)
    {
        //strategy should give you all the details you need
    }
}

答案 1 :(得分:0)

想象一下你有一个StategyViewModel。如果您的视图提供多种类型,您会发现以超类型(&#39; ViewModel&#39;类型)组织这些类型更容易。

了解The MVVM Pattern

在这种情况下,而不是......

型号:

public class Strategy
{
    public string name;

    // all your other properties...
}

查看:

@model WebApplication2.Models.Strategy

    <!-- present some stuffs... -->

控制器:

public ActionResult Index()
{
    var strategy = new Strategy();  // a concrete model type/class

    // do some stuffs...

    // using ViewBag to pass a bag of stuffs...

    return View(strategy);
}

改变这个......

ViewModel:

public class StrategyViewModel
{
    public Strategy strategy;
    public string someString;  // instead of ViewBag'ing everything?
}

查看:

@model WebApplication2.ViewModels.StrategyViewModel

    <!-- present some stuffs... -->

控制器:

public ActionResult Index()
{
    var vm = new StrategyViewModel();

    // do some stuffs...

    return View(vm);
}