【问题标题】:how to call model class in controller class如何在控制器类中调用模型类
【发布时间】:2023-04-09 19:35:01
【问题描述】:

mvc4

这是我在控制器文件夹中的控制器类

public class UserController : Controller
{
    //
    // GET: /User/
    private static Users _users = new Users();
    public ActionResult Index()
    {
        return View(_users._userList);
    }

    public ActionResult UserAdd()
    {
        return View();
    }
    [HttpPost]
    public ActionResult UserAdd(UserModels userModel)
    {
        _users.CreateUser(userModel);
        return View();
    }

}

错误 2 找不到类型或命名空间名称“用户”

错误 3 找不到类型或命名空间名称“UserModels”

这是我在模型文件夹中的用户类

 public class Users
    {
        public Users()
        {
            _userList.Add(new UserModels
            {
                FirstName = "birbal ",
                LastName = "kumar",
                Address = "new delhi",
                Email = "example@gmail.com",
                DOB = Convert.ToDateTime("2/11/1991"),
                salary = 8000
            });
         }
    }

这是我在模型文件夹中的用户模型类

public class UserModels
{
    [DisplayName("First Name")]
    [Required(ErrorMessage="First name is required")]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    public string Address { get; set; }
    [Required()]
    [StringLength(50)]
    public string Email { get; set; }
    [DataType(DataType.Date)]
    public DateTime DOB { get; set;  }
    [Range(100,1000000)] 
    public decimal salary { get; set; }
}

如何消除我的错误

【问题讨论】:

  • 尝试使用using语句using Yournamespace.Model导入模型文件夹
  • 上课前有没有命名空间块

标签: c# asp.net class asp.net-mvc-4 controller


【解决方案1】:

您没有包含模型的命名空间。

只需右键单击控制器中的 Users 类名,然后转到 Resolve 并从它们中将其命名空间包含在控制器类中。

如果你想明确地这样做,你的项目命名空间 assming MyProject,这样做:

using MyProject.Models;


public class UserController : Controller
{
   private static Users _users = new Users();
}

或者您可以像这样使用完全限定名称

public class UserController : Controller
{
  private static MyProject.Models.Users _users = new MyProject.Models.Users();
}

【讨论】:

    【解决方案2】:

    如果您的模型在同一个项目中,请尝试使用 using 语句导入您的模型文件夹。否则添加您的模型可用的项目的引用。

    using Yournamespace.Model;
    

    【讨论】:

      【解决方案3】:

      您需要添加对包含模型类的程序集的引用,并使用模型类的命名空间将“using XXXXX”语句添加到您的文件中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多