【问题标题】:Having issue while trying to pass two model to the same view at a time in mvc 3尝试在 mvc 3 中一次将两个模型传递到同一个视图时出现问题
【发布时间】:2012-10-11 06:13:43
【问题描述】:

我正在尝试为我的简单博客网站创建我的个人资料类型页面。我有两个像这样的简单模型类:

public class UserInfoModel
{

    public string UserName { get; set; }


    public string Email { get; set; }


    public string Password { get; set; }


    public string ConfirmPassword { get; set; }



}


public class NewPost
{

    public string PostTitle { get; set; }


    public string PostStory { get; set; }

}

我创建了一个用户和帖子的联合模型类,可以像这样传递给视图:

public class UserPostModel
{
    public UserInfoModel User { get; set; }
    public NewPost Post { get; set; }
}

我写的检索用户和帖子信息的方法是这样的:

public int GetUserID(string _UserName)
    {
        using (var context = new TourBlogEntities1())
        {
            var UserID = from s in context.UserInfoes
                         where s.UserName == _UserName
                         select s.UserID;
            return UserID.Single();

        }
    }

    public UserInfo GetUserDetails(int _UserID)
    {
        using (var context = new TourBlogEntities1())
        {
            var UserDetails = (from s in context.UserInfoes
                              where s.UserID == _UserID
                              select s).Single();
            return UserDetails;
        }
    }

    public Post GetUserPosts(int _UserID)
    {
        using (var context = new TourBlogEntities1())
        {
            var entity = (from s in context.Posts
                         where s.UserID == _UserID
                         select s).Single();

            return entity;
        }
    }

最后我从我的控制器操作中调用我的所有方法,如下所示:

[Authorize]
   public ActionResult MyProfile()
   {
       var Business = new Business();
       var UserID=Business.GetUserID(User.Identity.Name);
       var UserEntity=Business.GetUserDetails(UserID);
       var PostEntity=Business.GetUserPosts(UserID);




       var model = new UserPostModel();
       model.User.UserName = UserEntity.UserName; // problem showing here
       model.User.Email = UserEntity.Email;
       model.Post.PostTitle = PostEntity.PostTitle;
       model.Post.PostStory = PostEntity.PostStory;




       return View("MyProfile",model);
   }

显示类似“对象未引用对象类型或空对象”的运行时错误。在传递单个模型时,我以非常相似的方式工作得很好。我在这里做错了什么?

【问题讨论】:

    标签: asp.net-mvc-3 view model


    【解决方案1】:

    修改了你的 UserPostModel

    public class UserPostModel
    {
        public UserPostModel()
        {
           User = new UserInfoModel();
           Post = new Post();   
        }
        public UserInfoModel User { get; set; }
        public NewPost Post { get; set; }
    }
    

    注意:在设置为模型之前检查每个值,它不应为空。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-02
      • 2011-08-20
      • 2018-01-18
      • 2014-04-03
      • 2016-08-30
      • 1970-01-01
      • 2011-07-29
      • 1970-01-01
      相关资源
      最近更新 更多