加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – MVC 4 – 在局部视图中使用不同的模型

发布时间:2020-12-15 18:47:31 所属栏目:asp.Net 来源:网络整理
导读:请忍受我的noobness,我是MVC模式的超新人。 我想做什么 我在我的网站上为注册用户建立个人资料信息页面。该页面将列出用户的数据,例如出生日期,电话号码,订阅状态等。您可以获得想法。我还希望有一个表单让用户在同一页面上更改他们的密码,电子邮件地址
请忍受我的noobness,我是MVC模式的超新人。

我想做什么

我在我的网站上为注册用户建立个人资料信息页面。该页面将列出用户的数据,例如出生日期,电话号码,订阅状态等。您可以获得想法。我还希望有一个表单让用户在同一页面上更改他们的密码,电子邮件地址和个人信息。

我的问题

用户的数据通过传递的模型变量来自我的控制器:

public ActionResult Profil()
        {
            var model = db.Users.First(e => e.UserName == WebSecurity.CurrentUserName);
            return View(model);
        }

在我看来,输出如下:

<label>Phone number: </label>
            @if (Model.PhoneNumber != null)
                    {
                        @Model.PhoneNumber
                    }
                    else
                    {
                        <span class="red">You haven't set up your phone number yet. </span>
                    }

用户可以更改其信息的形式将使用另一个模型ProfileModel。所以基本我需要使用两个模型在我的看法,一个用于输出信息,一个用于发布数据。我以为使用部分视图我可以实现这一点,但我得到这个错误:

The model item passed into the dictionary is of type
‘Applicense.Models.User’,but this dictionary requires a model item of
type ‘Applicense.Models.ProfileModel’.

这是我对局部视图的呼吁如下所示:

@using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary()

        @Html.Partial("_ModifyProfileInfo")
    }

这是部分视图:

@model Applicense.Models.ProfileModel
<ul>
    <li>
        @Html.LabelFor(m => m.Email)
        @Html.EditorFor(m => m.Email)
    </li>
    <li>
        @Html.LabelFor(m => m.ConfirmEmail)
        @Html.EditorFor(m => m.ConfirmEmail)
    </li>
    <input type="submit" value="Update e-mail" />
</ul>

最后这是我的ProfileModel:

public class ProfileModel
    {
        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "New e-mail address")]
        public string Email { get; set; }

        [DataType(DataType.EmailAddress)]
        [Display(Name = "Confirm new e-mail address")]
        [Compare("Email",ErrorMessage = "The e-mail and it's confirmation field do not match.")]
        public string ConfirmEmail { get; set; }
    }

我缺少什么?这样做的正确方法是什么?

编辑:
我重写了我的代码,反映了Nikola Mitev的答案,但现在我还有另一个问题。这里是我得到的错误:

Object reference not set to an instance of an object. (@Model.UserObject.LastName)

这只发生在我发布更改的电子邮件地址值时。这是我的ViewModel(ProfileModel.cs):

public class ProfileModel
    {
        public User UserObject { get; set; }

        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "új e-mail cím")]
        public string Email { get; set; }

        [DataType(DataType.EmailAddress)]
        [Display(Name = "új e-mail cím meger?sítése")]
        [Compare("Email",ErrorMessage = "A két e-mail cím nem egyezik.")]
        public string ConfirmEmail { get; set; }

        [DataType(DataType.EmailAddress)]
        [Display(Name= "E-mail cím")]
        public string ReferEmail { get; set; }
    }

控制器:

public ActionResult Profil()
        {
            var User = db.Users.First(e => e.UserName == WebSecurity.CurrentUserName);

            var ProfileViewModel = new ProfileModel
            {
                UserObject = User
            };

            return View(ProfileViewModel);
        }

最后这里是我的user.cs模型类:

[Table("UserProfile")]
    public class User
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        [Column("UserName")]
        public string UserName { get; set; }
        [Column("Email")]
        [Required]
        public string Email { get; set; }
        [Column("FirstName")]
        public string FirstName { get; set; }
        [Column("LastName")]
        public string LastName { get; set; }
        [Column("PhoneNumber")]
        public string PhoneNumber { get; set; }
... You get the idea of the rest...

我在想,它正在发生,因为该模型试图将数据放在每个必需的列到数据库。

编辑2:
Profil操作的httppost方法:

[HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken]
        public ActionResult Profil(ProfileModel model)
        {
            if (ModelState.IsValid)
            {
//insert into database
                return Content("everything's good");
            }
            else
            {
//outputs form errors
                return View(model);
            }
        }

解决方法

处理这种情况的最好方法是使用并将viewModel传递给您的Profile控制器,viewModel是要传递给您的视图的多个对象的包装类。
public class ProfileUserViewModel
{
   public ProfileModel ProfileModelObject {get; set;}
   public UserModel  UserModelObject {get; set;}
}

您的控制器应如下所示:

public ActionResult Profil()
{            
    var profileModel = db.Users.First(e => e.UserName == WebSecurity.CurrentUserName);
    var userModel = //fetch from db.

    var pmViewModel = new ProfileUserViewModel  
                          {
                              ProfileModelObject = profileModel,UserModelObject = userModel
                          };

   return View(pmViewModel);
}

最后你的看法:

@model Applicense.Models.ProfileUserViewModel

<label>Phone number: </label>

@if (Model.ProfileModelObject.PhoneNumber != null)
{
   @Model.PhoneNumber
}
else
{
    <span class="red">You haven't set up your phone number yet. </span>
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读