简体   繁体   English

MVC4模型错误不正确

[英]MVC4 Incorrect model error

Hi I getting this error: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[DBModel.Telemarketing]', but this dictionary requires a model item of type 'TWeb.Models.LoginModel' 嗨,我收到此错误: 传递到字典中的模型项的类型为'System.Collections.Generic.List`1 [DBModel.Telemarketing]',但此字典需要类型为'TWeb.Models.LoginModel'的模型项

In _Layout.cshtml file i have 在_Layout.cshtml文件中我有

@Html.Partial("_LoginPartial") 

this partial login view is rendered in div on _layout page (it`s hides/shows with javaScripts ) 这个部分登录视图在_layout页面上的div中呈现(它用javaScripts隐藏/显示)

@model TWeb.Models.LoginModel

Then I have "Telemarketings" controller having view: 然后我有“Telemarketings”控制器有视图:

public class TelemarketingController : Controller
{
    private Entities db = new Entities();

    //
    // GET: /Telemarketing/

    public ActionResult Index()
    {
        return View(db.Telemarketings.ToList());
    }

When I click link in _Layout page 当我点击_Layout页面中的链接时

@Html.ActionLink("Telemarketingas", "Index", "Telemarketing", new{area="" },new{ })

It throws an error written in top of the post. 它会抛出一个写在帖子顶部的错误。

I am new in MVC, please help me. 我是MVC的新手,请帮帮我。

Your "_LoginPartial" expects "LoginModel" model, but since you're not giving it any, Razor engine sets its model to the current view model ("db.Telemarketings.ToList()"). 您的“_LoginPartial”需要“LoginModel”模型,但由于您没有提供任何模型,因此Razor引擎将其模型设置为当前视图模型(“db.Telemarketings.ToList()”)。

All you have to do is somehow set its model, probably like so: 所有你需要做的就是以某种方式设置它的模型,可能是这样的:

@Html.Partial("_LoginPartial", new LoginModel()) 

problem 1) Your Partial requires a model, and you're not passing one. 问题1)你的部分需要一个模型,你没有传递一个。 proper syntax: @Html.Partial("_LoginPartial", Model.LoginModel) 正确的语法: @Html.Partial("_LoginPartial", Model.LoginModel)

problem 2) _layout, as far as I know, can't have a Model passed 问题2) _layout,据我所知,不能传递模型

Solution 1: Use an ActionPartial. 解决方案1:使用ActionPartial。 AcionPartials are called similarly, AcionPartials类似地调用,

@Html.Action("/Tools/_LoginPartial"). 

The difference is they have an ActionMethod Associated which can return a Model 区别在于它们有一个可以返回模型的ActionMethod Associated

   public ActionResult _LoginPartial()
    {

          LoginModel Model= new LoginModel();
          //populate Model from whatever

         return View(Model);

    }

Option 2: Pass a LoginModel object to a Viewbag 选项2:将LoginModel对象传递给Viewbag

Viewbag.LoginModel = new LoginModel();

and reference the Viewbag in your _layout's Partial 并在_layout的Partial中引用Viewbag

@Html.Partial("_LoginPartial", Viewbag.LoginModel) 

最简单的方法是从Login Div :)中删除模型声明。

您可以使用此代码

 @Html.Partial("Partial page", new ModelFroLogin()) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM