Reputation: 101
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'.
PROBLEM:
Ошибка сервера в приложении '/'.
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");
I try to use one PartialView to use at the main page to view for user field for Login and Password to Sign In at Site.And another partial view for present to user list of Products at site. But I have problem, please help me with her.
this is example of my logon page
@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">
Войти через:
<a href="" style="text-decoration:none;"><img alt="" class="SocialIcon" src="../../Content/img/VKicon.PNG" /> </a>
<a href="" style="text-decoration:none"><img alt="" class="SocialIcon" src="../../Content/img/FBIcon.PNG" /> </a>
<a href="" style="text-decoration:none"><img alt="" class="SocialIcon" src="../../Content/img/TwitterIcon.PNG" /></a>
</div>
</div>
}
this is example of my search page which required another model that 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>
Account Conroller
[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" });
}
Controller which work with Search View
[HttpGet]
public ActionResult Search(string KeyWord)
{
DataManager dm = new DataManager();
List<Product> sended = dm.FindProducts(KeyWord);
return View(sended);
}
Upvotes: 2
Views: 1466
Reputation: 1039268
So you have 2 partial views LogOn.cshtml and Search.cshtml strongly typed respectively to LogOnModel
and IEnumerable<Product>
. This means that you need to pass the correct model types when rendering those partials. For example if you only use the Html.Partial("somePartial")
without specifying a model as second argument, the parent model will be passed. If you wanted to specify a model you could do the following:
@{
var logonModel = new LogOnModel();
}
@Html.Partial("~/Views/Account/LogOn.cshtml", logonModel)
or you could use the Html.Action helper which instead of directly including a partial view allows you to invoke a controller action that will return a partial. But there's no separate HTTP request being sent from the client. All happens in the same request:
@Html.Action("LogOn", "Account")
and now your LogOn method will be invoked and must pass the correct model:
public ActionResult LogOn()
{
var model = new LogOnModel();
return PartialView(model);
}
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
...
}
The same stands true for the search partial:
@Html.Action("Search", "SomeControllerContainingTheSearchAction")
Upvotes: 3