Asp.net-Mvc

視圖中無法辨識 ViewModel

  • August 24, 2021

我在不同項目(類庫)中的視圖模型。我添加了參考。但是當我從我的 mvc4 視圖中呼叫它時,比如@model Fancy.Management.Model.Home.IndexModel。查看不認識它。我不知道是什麼問題。我的視圖如下所示:

@model Fancy.Management.Model.Home.IndexModel
<html>
<head>
   <title>Giriş</title>
</head>
<body>
  @Html.BeginForm(){
    <table>
       <tr>
           <td>Kullanıcı Adı:</td>
           <td>@Html.TextBoxFor(m=>m.UserName)</td>
       </tr>
       <tr>
           <td>Şifre:</td>
           <td>@Html.PasswordFor(m=>m.Password)</td>
       </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Giriş" /></td>
        </tr>
   </table>
   }
</body>
</html>

我的控制器如下圖所示:

namespace Fancy.Web.Management.Controllers
{
#region Using Directives
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
#endregion

public class HomeController : Controller
{
   #region Get
   public ActionResult Index()
   {
       return View();
   } 
   #endregion

}
}

我的模型如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Fancy.Management.Model.Home
{
public class IndexModel
{
   public string UserName { get; set; }
   public string Password { get; set; }
}
}

您向模型添加了參考?好的,這還不足以讓您的視圖看到它。

首先,打開文件Views夾中的 web.config 文件。然後,為您的模型類添加一個命名空間標籤,如下所示:

<system.web.webPages.razor>
// ...
<pages pageBaseType="System.Web.Mvc.WebViewPage">
 <namespaces>
   // ...
   <add namespace="Fancy.Management.Model" />
   // ...
 </namespaces>
</pages>

最後改變你@model的看法,如下所示:

@model Home.IndexModel

問題應該消失了…

像這樣使用

public class HomeController : Controller
{
  #region Get
  public ActionResult Index()
  {
       IndexModel inModel=new IndexModel();
       return View(inModel);
  } 
  #endregion

}
}

引用自:https://stackoverflow.com/questions/17767339