首页 文章

在部分视图和LogOn中与模型冲突

提问于
浏览
2

传递到字典中的模型项的类型为'System.Collections.Generic.List`1 [PM.Models.Product]',但此字典需要类型为'PM.Models.LogOnModel'的模型项 .

问题:

Ошибка сервера в приложении '/'.
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[PM.Models.Product]', but this dictionary requires a model item of type 'PM.Models.LogOnModel'. 
 Описание: Необработанное исключение при выполнении текущего веб-запроса. Изучите трассировку стека для получения дополнительных сведений о данной ошибке и о вызвавшем ее фрагменте кода. 

 Сведения об исключении: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[PM.Models.Product]', but this dictionary requires a model item of type 'PM.Models.LogOnModel'.

Ошибка источника: 

Строка 1:  @using PM.Models
Строка 2:  @{PM.Models.LogOnModel LOM=new LogOnModel();}
Строка 3:  @RenderPage("../Account/LogOn.cshtml");

我尝试在主页面上使用一个PartialView来查看登录的用户字段和在站点登录的密码 . 另一个局部视图,用于在站点上显示产品的用户列表 . 但我有问题,请帮助我 .

这是我的登录页面的示例

@model PM.Models.LogOnModel
@{
    ViewBag.Title = "Log On";
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
    var UserNameTextBox = document.getElementById("login");
    UserNameTextBox.textContent = UserNameTextBox.textContent + "123";
</script>


<link href="../../Content/themes/our/Style.css" rel="stylesheet" type="text/css" />

@using (Html.BeginForm("LogOn", "Account"))
{      
   <div id="login" >
    @Html.TextBoxFor(m => m.UserName, new { @class = "inputLogin" })
    @Html.PasswordFor(m => m.Password, new { @class = "inputLogin" })
    @Html.CheckBoxFor(m => m.RememberMe)
    @Html.LabelFor(m => m.RememberMe, new { @class = "rememberText" })
    <div id="ErrorMessage">
    @Html.ValidationSummary(true, "Авторизоваться не удалось, проверьте введенные данные.")
    </div>

     <div id="loginButtons">
            @Html.ActionLink(" ", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink", @class = "register" })
            <input type="submit" value="Войти" id="loginButton" title="Войти" />
        </div>
    <div id="loginWith">
        Войти через: &nbsp;&nbsp;&nbsp;
        <a href="" style="text-decoration:none;"><img alt="" class="SocialIcon" src="../../Content/img/VKicon.PNG" />&nbsp;&nbsp;&nbsp;&nbsp;</a>
        <a href="" style="text-decoration:none"><img alt="" class="SocialIcon" src="../../Content/img/FBIcon.PNG" />&nbsp;&nbsp;&nbsp;</a>
        <a href="" style="text-decoration:none"><img alt="" class="SocialIcon" src="../../Content/img/TwitterIcon.PNG" /></a>
    </div>
   </div>

}

这是我的搜索页面的示例,它需要另一个LogOn模型

@model IEnumerable<PM.Models.Product>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Description)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Type)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Image)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Partition)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Description)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Type)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Image)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Partition)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

</table>

帐户控制器

[AllowAnonymous]
        public ActionResult LogOn()
        {
            string actionName = ControllerContext.RouteData.GetRequiredString("action");
            ViewBag.FormAction = actionName;
            return View();
        }


        //
        // POST: /Account/LogOn

        [AllowAnonymous]
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (System.Web.Security.Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        if (Request.UrlReferrer != null)
                            return Redirect(Request.UrlReferrer.AbsoluteUri);
                        else
                        {
                            return RedirectToAction("Index","Home");
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return RedirectToAction("Index", "Home", new { login = "incorrect" });
        }

与Search View配合使用的控制器

[HttpGet]
    public ActionResult Search(string KeyWord)
    {
        DataManager dm = new DataManager();
        List<Product> sended = dm.FindProducts(KeyWord);
        return View(sended);
    }

1 回答

  • 2

    因此,您有两个部分视图LogOn.cshtml和Search.cshtml分别强烈键入 LogOnModelIEnumerable<Product> . 这意味着在渲染这些部分时需要传递正确的模型类型 . 例如,如果仅使用 Html.Partial("somePartial") 而未将模型指定为第二个参数,则将传递父模型 . 如果要指定模型,可以执行以下操作:

    @{
        var logonModel = new LogOnModel();
    }
    @Html.Partial("~/Views/Account/LogOn.cshtml", logonModel)
    

    或者您可以使用Html.Action帮助程序,而不是直接包含部分视图允许您调用将返回部分的控制器操作 . 但是没有从客户端发送单独的HTTP请求 . 所有都发生在同一个请求中:

    @Html.Action("LogOn", "Account")
    

    现在你的LogOn方法将被调用,并且必须传递正确的模型:

    public ActionResult LogOn()
    {
        var model = new LogOnModel();
        return PartialView(model);
    }
    
    [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        ...
    }
    

    搜索部分也是如此:

    @Html.Action("Search", "SomeControllerContainingTheSearchAction")
    

相关问题