ข้อขัดแย้งกับโมเดลในมุมมองบางส่วนและการเข้าสู่ระบบ

รายการโมเดลที่ส่งเข้าสู่พจนานุกรมเป็นประเภท 'System.Collections.Generic.List`1[PM.Models.Product]' แต่พจนานุกรมนี้ต้องการรายการโมเดลประเภท 'PM.Models.LogOnModel'

ปัญหา:

Ошибка сервера в приложении '/'.
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");

ฉันพยายามใช้ PartialView หนึ่งอันเพื่อใช้ที่หน้าหลักเพื่อดูฟิลด์ผู้ใช้สำหรับการเข้าสู่ระบบและรหัสผ่านเพื่อลงชื่อเข้าใช้ที่ไซต์ และอีกมุมมองบางส่วนสำหรับนำเสนอรายการผู้ใช้ของผลิตภัณฑ์ที่ไซต์ แต่ฉันมีปัญหา โปรดช่วยฉันด้วยเธอ

นี่คือตัวอย่างหน้าเข้าสู่ระบบของฉัน

@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="/th../../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">
        Войти через: &nbsp;&nbsp;&nbsp;
        <a href="/th" style="text-decoration:none;"><img alt="" class="SocialIcon" src="../../Content/img/VKicon.PNG" />&nbsp;&nbsp;&nbsp;&nbsp;</a>
        <a href="/th" style="text-decoration:none"><img alt="" class="SocialIcon" src="../../Content/img/FBIcon.PNG" />&nbsp;&nbsp;&nbsp;</a>
        <a href="/th" style="text-decoration:none"><img alt="" class="SocialIcon" src="../../Content/img/TwitterIcon.PNG" /></a>
    </div>
   </div>

}

นี่คือตัวอย่างหน้าค้นหาของฉันซึ่งต้องใช้โมเดลอื่นที่เข้าสู่ระบบ

@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>

ผู้ควบคุมบัญชี

 [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" });
        }

คอนโทรลเลอร์ที่ทำงานร่วมกับ Search View

[HttpGet]
    public ActionResult Search(string KeyWord)
    {
        DataManager dm = new DataManager();
        List<Product> sended = dm.FindProducts(KeyWord);
        return View(sended);
    }

person Andrew Kubrin    schedule 13.04.2012    source แหล่งที่มา
comment
คุณสามารถแสดงการทำงานของคอนโทรลเลอร์ที่ตอบสนองได้หรือไม่?   -  person Steve Mallory    schedule 14.04.2012
comment
ใช่ ฉันเพิ่มพวกเขาเมื่อไม่กี่นาทีที่แล้ว   -  person Andrew Kubrin    schedule 14.04.2012
comment
ในตัวอย่างของคุณ คุณมีคอนโทรลเลอร์หนึ่งตัวมากกว่าที่คุณมีมุมมองที่พิมพ์อย่างมากซึ่งสร้างขึ้นสำหรับมัน จากนั้นคุณจึงส่งต่อโมเดลอื่นไปยังมุมมองที่พิมพ์อย่างยิ่งซึ่งไม่ได้รับการยอมรับ ดังนั้นคุณได้รับข้อผิดพลาดนี้   -  person COLD TOLD    schedule 14.04.2012
comment
ใช่ ฉันสร้างมุมมองที่พิมพ์อย่างเข้มงวด ใช้อันหนึ่งเพื่อนำเสนอแบบฟอร์มผู้ใช้เพื่อเข้าสู่ระบบ และอีกอันใช้เพื่อนำเสนอผลลัพธ์ของการค้นหาให้เขา โปรดพูดว่าฉันจะทำสิ่งนี้ได้อย่างไร หรือถ้าฉันใช้มุมมองที่พิมพ์อย่างเข้มงวด ฉันไม่สามารถใช้สองมุมมองได้ และฉันต้องใช้วิธีอื่นในการถ่ายโอนข้อมูลจากคอนโทรลเลอร์ไปยัง View เช่น ViewData เป็นต้น   -  person Andrew Kubrin    schedule 14.04.2012


คำตอบ (1)


ดังนั้นคุณจึงมี 2 มุมมองบางส่วน LogOn.cshtml และ Search.cshtml พิมพ์อย่างยิ่งตามลำดับเป็น LogOnModel และ IEnumerable<Product> ซึ่งหมายความว่าคุณจะต้องส่งประเภทโมเดลที่ถูกต้องเมื่อเรนเดอร์บางส่วนเหล่านั้น ตัวอย่างเช่น หากคุณใช้เฉพาะ Html.Partial("somePartial") โดยไม่ระบุโมเดลเป็นอาร์กิวเมนต์ที่สอง โมเดลหลักจะถูกส่งผ่าน หากคุณต้องการระบุรุ่น คุณสามารถดำเนินการดังต่อไปนี้:

@{
    var logonModel = new LogOnModel();
}
@Html.Partial("~/Views/Account/LogOn.cshtml", logonModel)

หรือคุณสามารถใช้ตัวช่วย Html.Action ซึ่งแทน การรวมมุมมองบางส่วนโดยตรงทำให้คุณสามารถเรียกใช้การดำเนินการของคอนโทรลเลอร์ที่จะส่งคืนบางส่วนได้ แต่ไม่มีการส่งคำขอ HTTP แยกต่างหากจากไคลเอนต์ ทั้งหมดเกิดขึ้นในคำขอเดียวกัน:

@Html.Action("LogOn", "Account")

และตอนนี้วิธีการ LogOn ของคุณจะถูกเรียกใช้และจะต้องผ่านโมเดลที่ถูกต้อง:

public ActionResult LogOn()
{
    var model = new LogOnModel();
    return PartialView(model);
}

[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    ...
}

เช่นเดียวกับการค้นหาบางส่วน:

@Html.Action("Search", "SomeControllerContainingTheSearchAction")
person Darin Dimitrov    schedule 14.04.2012