如何将值从数据库映射到MVC 4中的视图模型



我遇到了什么应该是一个非常简单的任务的麻烦。我试图映射值从数据库检索到视图模型。然后我想把它作为模型传递给我的视图。

视图模型被称为EditAdminModelVM,它包含了一个更大的类UserProfile的属性的较小子集。我选择使用视图模型,因为我不希望用户能够更新整个域模型,而只是其中的一些。

这是ViewModel:

public class EditAdminModelVM
{
    [Required]
    [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.")]
    [Display(Name = "First name")]
    public string FirstName { get; set; }
    [Required]
    [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.")]
    [Display(Name = "Last name")]
    public string LastName { get; set; }
    [Required]
    [MaxLength(250)]
    [EmailAddress]
    public string Email { get; set; }
    [Required]
    //[Remote("doesUserNameExist", "Account", HttpMethod = "POST", ErrorMessage = "Username already exists. Please enter a different User Name.")] //note this checks from client-side only - server side check is built in to membership
    [Display(Name = "Username")]
    public string UserName { get; set; }
    [HiddenInput]
    public int UserId { get; set; }
}

这是控制器(虽然它不工作):

[Authorize(Roles = "Admin")]
    public ActionResult EditAdmin(int id = 0)
    {
        PpDB db = new PpDB();
        var viewModel = new EditAdminModelVM();
        viewModel = db.UserProfiles
             .Where(x => x.UserId == id)
             .Select(x => new EditAdminModelVM
             {
                 FirstName = x.FirstName,
                 LastName = x.LastName,
                 Email = x.Email,
                 UserName = x.UserName
             });
        return View(viewModel);
    }

在这个例子中,. select用一个潦草的下划线表示一些关于IQueryable。但如果我尝试设置var viewModel = new IQueryable;我得到另一个错误。

我想这可能是语法问题。这个DB查询应该只返回一行,所以我不认为IQueryable是必要的,但我不是专家。

如果你能给我提供一个如何构建这个代码块的工作示例,那么我可以通过例子来学习-对我疲惫的大脑更好。

感谢!

更新KEN下面是更新后的控制器:

 [Authorize(Roles = "Admin")]
    public ActionResult EditAdmin(int id = 0)
    {
        PpDB db = new PpDB();
        List<EditAdminModelVM> viewModel = new List<EditAdminModelVM>();
        viewModel = db.UserProfiles
             .Where(x => x.UserId == id)
             .Select(x => new EditAdminModelVM
             {
                 FirstName = x.FirstName,
                 LastName = x.LastName,
                 Email = x.Email,
                 UserName = x.UserName,
                 UserId = x.UserId
             }).ToList();
        return View(viewModel);
    }

下面是视图:

@model List<PpModels.Models.EditAdminModelVM>

@{
    ViewBag.Title = "Edit Admin";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
<fieldset>
    <legend>UserProfile</legend>
    @Html.HiddenFor(model => model.UserId)
    <div class="editor-label">
        @Html.LabelFor(model => model.UserName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.UserName)
        @Html.ValidationMessageFor(model => model.UserName)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.FirstName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.LastName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Email)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Email)
        @Html.ValidationMessageFor(model => model.Email)
    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

var viewModel = new EditAdminModelVM();更改为List<EditAdminModelVM> viewModel = new List<EditAdminModelVM>();,并将ToList()添加到db.UserProfiles查询的末尾。现在,这将把EditAdminModelVM的集合传递给视图。在视图中遍历该集合以获得所需的输出。

Update: For single instance:

[Authorize(Roles = "Admin")]
public ActionResult EditAdmin(int id = 0)
{
    PpDB db = new PpDB();
    var viewModel = new EditAdminModelVM();
    viewModel = db.UserProfiles
         .Where(x => x.UserId == id)
         .Select(x => new EditAdminModelVM
         {
             FirstName = x.FirstName,
             LastName = x.LastName,
             Email = x.Email,
             UserName = x.UserName
         }).FirstOrDefault();
    return View(viewModel);
}

对于这个,你不需要在视图中迭代:

在视图中使用@model ProofPixModels.Models.EditAdminModelVM

相关内容

  • 没有找到相关文章

最新更新