经过这么多年使用ASP.Net,我仍然试图找出如何使用MVC实现相同的结果。MVC - 多个强类型的对象...在一个视图
我有一个控件强类型的东西的materpage。当我导航到不同的强类型模型的视图...并单击按钮执行某些操作时,我得到“传入字典的模型项目类型为Site.Models.RegisterModel”,但此字典需要模型“Site.Models.LogOnModel”类型的项目。
为了这个例子,我们可以使用VS 2010提供的Default MVC应用程序,让我们想象一下我想更改“LogonUserControl.ascx”,以便它告诉我登录的用户(因为它工作目前)或允许我从那里登录,向我显示用户名和密码的文本框(因此在这种情况下从主页)。
所以我采取了控制和强烈键入如下:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Gioby.Models.LogOnModel>" %>
<%
if (Request.IsAuthenticated) {
%>
Welcome <b><%: Page.User.Identity.Name %></b>
[ <%: Html.ActionLink("Log Off", "LogOff", "Account")%> ]
<%
}
else {
%>
<% using (Html.BeginForm()) { %>
<div id="logon">
<div class="editor-label">
<%: Html.LabelFor(m => m.UserName)%>
<%: Html.TextBoxFor(m => m.UserName)%>
<%: Html.ValidationMessageFor(m => m.UserName, "*") %>
<%: Html.LabelFor(m => m.Password)%>
<%: Html.PasswordFor(m => m.Password)%>
<%: Html.ValidationMessageFor(m => m.Password, "*") %>
<input type="submit" value="Log On" />
</div>
<div class="editor-label">
<%: Html.ActionLink("Register here", "Register", "Account")%>
<%: Html.CheckBoxFor(m => m.RememberMe, new { @class = "pad-left" })%>
<%: Html.LabelFor(m => m.RememberMe) %>
</div>
</div>
<% } %>
<%
}
%>
然后在HomeController中,我添加了一个程序为:
[HttpPost]
public ActionResult Index(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
// ==>> Check Login against your DB
// Now check if param returnUrl is empty
if (!String.IsNullOrEmpty(returnUrl))
return Redirect(returnUrl);
return RedirectToAction("Index", "Home");
}
// If we got this far, something failed, redisplay form
return View(model);
}
我在主页上测试它...它的工作原理!
但是,当我浏览到“注册”视图(请记住,“LogonUserControl.ascx”位于里面的“母版”,因此从注册视图中可见)。
所以,当我点击注册按钮,我得到的错误: 传递到字典的模型产品类型Site.Models.RegisterModel的”,但这部词典需要类型Site.Models.LogOnModel的模型项目”。
问: 是否意味着我将永远无法在不同拼凑成一个看法?
比方说,我想写一个电子商务网站,并在主页上我想看到“最常用的标签”,“大多数购买的产品”,“本月产品”,“类别列表”......所有相同的视图,每个人都有自己的HTTP POST操作。
如果这可以使用MVC?
您的'Register'控制器操作在哪里?你从上面的例子中忽略了它吗? – 2010-10-25 19:37:05