Asp.net mvc 传递到字典中的模型项是类型,但dicitonary需要类型为的模型项

Asp.net mvc 传递到字典中的模型项是类型,但dicitonary需要类型为的模型项,asp.net-mvc,Asp.net Mvc,我是ASP.NETMVC的初学者,我有一个相当奇怪的问题,我似乎无法解决如何解决。我通过谷歌找到了同一问题不同版本的多种解决方案,但它们似乎与我的问题无关。如果有人能帮我找出错误,我将不胜感激 编辑:我知道将@model app.Models.Authentication更改为@model app.Models.ContactMessage会修复它,但我不明白为什么,而且显然,建议的修复会给我带来一系列与表单相关的其他错误。 我的错误:传入字典的模型项的类型为“app.Models.Auth”,

我是ASP.NETMVC的初学者,我有一个相当奇怪的问题,我似乎无法解决如何解决。我通过谷歌找到了同一问题不同版本的多种解决方案,但它们似乎与我的问题无关。如果有人能帮我找出错误,我将不胜感激

编辑:我知道将@model app.Models.Authentication更改为@model app.Models.ContactMessage会修复它,但我不明白为什么,而且显然,建议的修复会给我带来一系列与表单相关的其他错误。

我的错误:传入字典的模型项的类型为“app.Models.Auth”,但此字典需要类型为“app.Models.ContactMessage”的模型项

相关问答:

堆栈跟踪:

[InvalidOperationException: The model item passed into the dictionary is of type 'app.Models.Authentication', but this dictionary requires a model item of type 'app.Models.ContactMessage'.]
System.Web.Mvc.ViewDataDictionary`1.SetModel(Object value) +378
System.Web.Mvc.ViewDataDictionary.set_Model(Object value) +47
System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary dictionary) +259
System.Web.Mvc.ViewDataDictionary`1..ctor(ViewDataDictionary viewDataDictionary) +37
System.Web.Mvc.WebViewPage`1.SetViewData(ViewDataDictionary viewData) +98
System.Web.Mvc.WebViewPage.set_ViewData(ViewDataDictionary value) +39
System.Web.Mvc.WebViewPage.ConfigurePage(WebPageBase parentPage) +267
System.Web.WebPages.<>c__DisplayClass3.<RenderPageCore>b__2(TextWriter writer) +318
System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +42
System.Web.WebPages.WebPageExecutingBase.WriteTo(TextWriter writer, HelperResult content) +45
System.Web.WebPages.WebPageBase.Write(HelperResult result) +53
System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +178
System.Web.WebPages.WebPageBase.PopContext() +229
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +154
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +695
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +321
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
  System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651188
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
客户控制员:

 public class HomeController : BaseController
{



    [HttpGet]
    public ActionResult Index()
    {

        ViewBag.Title="Portfolio";
        return View(new ContactMessage());
    }

    [HttpPost]
    public ActionResult Index(ContactMessage message)
    {
        if (ModelState.IsValid)
        {
            using (var db = new MessageDatabase())
            {

                message.DateSent = DateTime.Now;

                db.ContactMessages.Add(message);
                Success(string.Format("Message received! Thanks, I will try to get back to you as soon as possible."), true);
                db.SaveChanges();
            }

            TempData["ContactMessage"] = message;
            return RedirectToAction("Index");
        }
        Danger("Looks like something went wrong. Please check your form.");
        ViewBag.Title = "Portfolio";
        return View(message);
    }

   ...
}
public class AccountController : BaseController
{
//
    // GET: /Account/

    public ActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public ActionResult Login()
    {
        var authModel = new Authentication();
        return View(authModel);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Login(Authentication authModel)
    {
        if (!ModelState.IsValid)
        {
            return View(authModel);
        }

        if (WebSecurity.Login(authModel.Username, authModel.Password))
        {
            return new RedirectResult("/");
        }
        else
        {
            ViewBag.ErrorMessage = "The username and/or password was incorrect";
            return View(authModel);
        }

    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Logout(Authentication authModel)
    {


        if (WebSecurity.Login(authModel.Username, authModel.Password))
        {
            WebSecurity.Logout();
            Success("You have been logged off", true);
            return new RedirectResult("/");
        }

    }

    [HttpGet]
    public ActionResult Register()
    {
        return View(new Registration());
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Register(Registration authModel)
    {
        if (ModelState.IsValid)
        {
            if (!WebSecurity.UserExists(authModel.Username))
            {
                WebSecurity.CreateUserAndAccount(authModel.Username, authModel.Password);
                WebSecurity.Login(authModel.Username, authModel.Password, true);
                return new RedirectResult("/");
            }

            ViewBag.ErrorMessage = string.Format("The user {0} already exists. Please try a different username.",
                authModel.Username);
        }


        return View(authModel);
    }
}
导致问题的视图:

@model app.Models.Authentication


@{
ViewBag.Title = "Login";
}
<div class="container">
   <h2>Login</h2>

   <div class="form-horizontal">
       @if (WebSecurity.IsAuthenticated)
       {
          <p>You are currently logged in.</p>
       }
       else
       {
           <hr />
           <p>@ViewBag.ErrorMessage</p>
           using (Html.BeginForm())
           {
             @Html.AntiForgeryToken()
            <div class="form-group 12u">
                <p>
                    @Html.LabelFor(m => m.Username) @Html.ValidationMessageFor(m => m.Username)<br />
                    @Html.EditorFor(m => m.Username)
                </p>
            </div>
            <div class="form-group 12u">
                <p>
                    @Html.LabelFor(m => m.Password) @Html.ValidationMessageFor(m => m.Password)<br />
                    @Html.PasswordFor(m => m.Password)
                </p>
            </div>
            <div class="form-group 12u">
                <p>
                    <input type="submit" value="Login" />
                </p>
            </div>
            <div class="form-group 12u">
                <p>Don't have an account? @Html.ActionLink("Register", "Register")</p>
                <p>@Html.RouteLink("Return Home", new { controller = "Home" })</p>
            </div>
        }
    }
</div>

我认为您需要
返回重定向到操作(“ActionName”、“ControllerName”)
而不是
返回重定向结果(“Path”)

重定向到操作
-


RedirectResult
-

我认为您希望
返回RedirectToAction(“ActionName”、“ControllerName”)
而不是
返回RedirectResult(“Path”)

重定向到操作
-


RedirectResult
-

我最好的猜测是,可能在布局中的某个地方,您正在执行以下操作:

 @Html.Partial("_Contact")
@Html.Partial("_Contact", new ContactMessage())
打算把一个联系方式或者其他东西放到一个边栏区域。调用分部时,隐式传递当前视图的模型,与执行以下操作相同:

@Html.Partial("_Contact", Model)
如果partial不使用模型,那么这不一定会导致问题。但是,如果您的partial确实定义了一个模型,那么必须向它传递该类型的实例。您可以通过执行以下操作来修复它:

 @Html.Partial("_Contact")
@Html.Partial("_Contact", new ContactMessage())
但是,对于布局中的类似项,实际上应该使用子操作:

@Html.Action("Contact", "Home")

然后,您可以在
HomeController
中定义一个
Contact
操作,该操作将返回您的局部视图,并定义要与其一起传递的模型。这将使此块的呈现完全脱离页面其余部分的上下文,因此您不会像这里一样因上下文溢出而产生冲突。

我的最佳猜测是,在布局的某个地方,您可能正在执行以下操作:

 @Html.Partial("_Contact")
@Html.Partial("_Contact", new ContactMessage())
打算把一个联系方式或者其他东西放到一个边栏区域。调用分部时,隐式传递当前视图的模型,与执行以下操作相同:

@Html.Partial("_Contact", Model)
如果partial不使用模型,那么这不一定会导致问题。但是,如果您的partial确实定义了一个模型,那么必须向它传递该类型的实例。您可以通过执行以下操作来修复它:

 @Html.Partial("_Contact")
@Html.Partial("_Contact", new ContactMessage())
但是,对于布局中的类似项,实际上应该使用子操作:

@Html.Action("Contact", "Home")

然后,您可以在
HomeController
中定义一个
Contact
操作,该操作将返回您的局部视图,并定义要与其一起传递的模型。这将使该块的呈现完全脱离页面其余部分的上下文,因此您不会像这里一样从上下文中溢出冲突。

那么,该视图用于哪个控制器?如果是主视图,那么请查看您创建视图时使用的内容-a
ContactMessage
…上面的视图代码是针对AccountController的,当我尝试转到website.net/account/login或website.net/register时,它会显示错误。您可以发布您的路线吗?看起来您没有传递此操作的正确视图。您是否设置了断点并对此进行了调试以检查实际使用的控制器?我想您指的是RouteConfig文件。如果是这样的话,那么我已经这样做了(见文章末尾)。那么这是哪个控制器的视图?如果是主视图,那么请查看您创建视图时使用的内容-a
ContactMessage
…上面的视图代码是针对AccountController的,当我尝试转到website.net/account/login或website.net/register时,它会显示错误。您可以发布您的路线吗?看起来您没有传递此操作的正确视图。您是否设置了断点并对此进行了调试以检查实际使用的控制器?我想您指的是RouteConfig文件。如果是这样的话,那么我已经这样做了(见文章末尾)。