I’m developing a MVC 4 Web Site.
In my site I have a login form in a partial view and I’m rendering it in _layout.cshtml, it uses LoginModel.
I also have a contact form, it uses ContactModel
When I get to contact form and submit it everything is fine. It went to server side. After it executes I’m returning a view and binding it to ContactModel
Which is simply :
[HttpPost]
public ActionResult Contact(Contact model)
{
if (ModelState.IsValid)
{
//somecode here
}
return View(model);
}
It’s getting complicated and MVC tries to bind ContactModel to login page and gives the following error
The model item passed into the dictionary is of type
‘My_Project.Model.ContactModel’, but this dictionary requires a model
item of type ‘My_Project.Models.LoginModel’.
My contact form view :
@model My_Project.Model.ContactModel
@{
ViewBag.Title = "Contact";
}
@using (Html.BeginForm("Contact", "Home", FormMethod.Post, new { id = "formContact" }))
{
@Html.ValidationSummary(true)
@Html.TextBoxFor(model => model.Name, new {@class = "c2inp1", @placeholder = "Name"})
@Html.ValidationMessageFor(model => model.Name)
<br/>
@Html.TextBoxFor(model => model.Surname, new {@class = "c2inp2", @placeholder = "Surname"})
@Html.ValidationMessageFor(model => model.Surname)
<br/>
@Html.TextBoxFor(model => model.Email, new {@class = "c2inp2", @placeholder = "Email"})
@Html.ValidationMessageFor(model => model.Email)
<br/>
@Html.TextAreaFor(model => model.Message, new { @class = "c2inp3", @placeholder = "Message" })
@Html.ValidationMessageFor(model => model.Message)
<br/>
<input type="image" src="@Url.Content("~/Images/c2img4.png")" alt="" class="c2submit"/>
}
</div>
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
My login form in partial view
@model My_Project.Model.LoginModel
@{
ViewBag.Title = "Log in";
}
@if (WebSecurity.IsAuthenticated)
{
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
</hgroup>
<section id="loginForm">
<h2>Use a local account to log in.</h2>
@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Log in Form</legend>
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
</li>
<li>
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })
</li>
</ol>
<input type="submit" value="Log in" />
</fieldset>
}
</section>
</section>
}
In my _layout.cshtml im rendering login form
@Html.Partial("_LoginPartial")
How can I solve this issue?
You need to specify the model you want to pass to the login view in _layout.cshtml view…
Example: