Search code examples
asp.net-mvcasp.net-mvc-4

ViewModel not recognized in view


My viewmodel in different project(class library). I added reference. But when i call it from my mvc4 view like @model Fancy.Management.Model.Home.IndexModel. View not recognized it. What is the problem i dont know. My View is shown below:

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

My controller is shown below:

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

}
}

And my model is shown below:

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; }
}
}

Solution

  • You added a ref to the model? Ok, that's not enough in order that your view can see it.

    First, open the web.config file located in Views folder. Then, add a namespace tag for your model class like the following:

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

    and finally change your @model in your view like this:

    @model Home.IndexModel
    

    The problem should goes away...