正确的方法来填充ViewModel?

戴维斯(JD Davis)

我正在使用Web应用程序工作,并且正在使用标准的CRUD样式交互。但是,某些字段我不希望用户更新,因此我从视图中将其删除。但是,如果我未明确设置这些字段,则在数据库中更新模型时将清除它们。

我担心的是为ViewModel填充字段的正确方法是什么。

我想到的一个大概主意是这样的:

我的视图模型:

public class EditSoftwareTrackingViewModel 
{
    public EditSoftwareTrackingViewModel(SoftwareTracking model)
    {
        Id = model.Id;
        SoftwareId = model.SoftwareId;
        ComputerId = model.ComputerId;
        SoftwareActionId = model.SoftwareActionId;
        LastModified = model.LastModified;
        Computer = model.Computer;
        Software = model.Software;
        SoftwareAction = model.SoftwareAction;
    }
    public int Id { get; set; }
    [DisplayName("Software")]
    public int SoftwareId { get; set; }
    [DisplayName("Computer")]
    public int ComputerId { get; set; }
    [DisplayName("Software Action")]
    public int SoftwareActionId { get; set; }
    [DisplayName("Last Modified")]
    public DateTime? LastModified { get; set; }

    public virtual Computer Computer { get; set; }
    public virtual Software Software { get; set; }
    public virtual SoftwareAction SoftwareAction { get; set; }
}

我的主要模特

[Table("asset.SoftwareTracking")]
public partial class SoftwareTracking
{
    public int Id { get; set; }
    [DisplayName("Software")]
    public int SoftwareId { get; set; }
    [DisplayName("Computer")]
    public int ComputerId { get; set; }
    [DisplayName("Date Entered")]
    public DateTime? EnteredDate { get; set; }
    [DisplayName("Software Action")]
    public int SoftwareActionId { get; set; }
    [DisplayName("Last Modified")]
    public DateTime? LastModified { get; set; }

    public virtual Computer Computer { get; set; }
    public virtual Software Software { get; set; }
    public virtual SoftwareAction SoftwareAction { get; set; }
}

和我的控制器使用视图模型

    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        EditSoftwareTrackingViewModel softwaretracking = new EditSoftwareTrackingViewModel(db.SoftwareTrackings.Find(id));
        if (softwaretracking == null)
        {
            return HttpNotFound();
        }
        GeneratePageData(softwaretracking.Software.Id);
        return View(softwaretracking);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(EditSoftwareTrackingViewModel softwaretracking)
    {
        if (ModelState.IsValid)
        {
            softwaretracking.LastModified = DateTime.Now;
            var softwareTrack = db.SoftwareTrackings.Find(softwaretracking.Id);
            softwareTrack = new SoftwareTracking
            {
                Computer = softwaretracking.Computer,
                ComputerId = softwaretracking.ComputerId,
                LastModified = softwaretracking.LastModified,
                Software = softwaretracking.Software,
                SoftwareAction = softwaretracking.SoftwareAction,
                SoftwareActionId = softwaretracking.SoftwareActionId,
                SoftwareId = softwaretracking.SoftwareId,
                EnteredDate = softwareTrack.EnteredDate
            };

            db.Entry(softwareTrack).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        GeneratePageData(softwaretracking.Software.Id);
        return View(softwaretracking);
    }

有更好的选择吗?还是应该继续以这种方式创建视图模型?

编辑

我的业务逻辑和观点

    private void GeneratePageData(int? id = null)
    {

        ViewBag.Computers = new SelectList(db.Computers, "Id", "ComputerName");
        ViewBag.SoftwareActions = new SelectList(db.SoftwareActions, "Id", "ActionPerformed");

        var usedSoft = (from softTrack in db.SoftwareTrackings
                        where (softTrack.SoftwareActionId != 3)
                        select softTrack.Software);

        var softwareList = (from soft in db.Softwares
                            where (
                                ((from softTrack in db.SoftwareTrackings
                                  where (softTrack.SoftwareActionId != 3 && softTrack.SoftwareId == soft.Id)
                                  select softTrack.Software).Count() < soft.KeyQuantity)
                                && !(soft.AssetStatusId == 4 || soft.AssetStatusId == 5)
                                || soft.Id == id)
                            select soft).ToList();

        ViewBag.SoftwareList = softwareList.Select(t => new SelectListItem
        {
            Text = t.SoftwareIdNameFull,
            Value = t.Id.ToString()
        });

    }

我的看法

@model Lighthouse_Asset_Manager.Models.EditSoftwareTrackingViewModel

@{
    ViewBag.Title = "Edit Software Install";
    Layout = "";
}

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
        &times;
    </button>
    <h4 class="modal-title" id="myModalLabel">Edit Software Install</h4>
</div>
<div class="modal-body">

    @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "computerForm" }))
    {
        @Html.AntiForgeryToken()
        @Html.HiddenFor(model => model.Id)

        <div class="form-horizontal">
            @Html.ValidationSummary(true)


            <div class="form-group">
                @Html.LabelFor(model => model.SoftwareId, "Software", new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("SoftwareId", (IEnumerable<SelectListItem>)ViewBag.SoftwareList, "-- Select --", new
                    {
                        @style = "width:100%",
                        @class = "select2"
                    })
                    @Html.ValidationMessageFor(model => model.SoftwareId)
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.ComputerId, "Computer", new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("ComputerId", (IEnumerable<SelectListItem>)ViewBag.Computers, "-- Select --", new
                    {
                        @style = "width:100%",
                        @class = "select2"
                    })
                    @Html.ValidationMessageFor(model => model.ComputerId)
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.SoftwareActionId, "Action", new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("SoftwareActionId", (IEnumerable<SelectListItem>)ViewBag.SoftwareActions, "-- Select --", new
                    {
                        @style = "width:100%",
                        @class = "form-control"
                    })
                    @Html.ValidationMessageFor(model => model.SoftwareActionId)
                </div>
            </div>


            <div class="form-actions no-color">
                <button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-floppy-o"></i> Edit Install Record</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">
                    Cancel
                </button>
            </div>
        </div>
    }
</div>
用户名

您使用视图模型的方法是一个很好的方法。对这些问题的答案这个问题解释了一些好处,包括防止过度张贴攻击,使用视图特定的显示和验证属性和包括查看特定的属性,如SelectLists自动映射器之类的工具可以使您轻松在数据之间进行映射和查看模型,并减少控制器中的代码。我建议您对视图模型进行一些更改。LastModifiedComputerSoftwareSoftwareAction性能不要求(你不绑定到这些),我将包括SelectList模型的属性而不是ViewBag

查看模型

public class EditSoftwareTrackingViewModel 
{
  public int Id { get; set; }
  [Display(Name="Software")]
  public int SoftwareId { get; set; }
  [Display(Name="Computer")]
  public int ComputerId { get; set; }
  [Display(Name="Software Action")]
  public int SoftwareActionId { get; set; }
  public SelectList Computers { get; set; }
  public SelectList SoftwareActions{ get; set; }
  public SelectList SoftwareList{ get; set; }
}

然后更改GeneratePageData()方法以接受视图模型

private void GeneratePageData(EditSoftwareTrackingViewModel model)
{
  model.Computers = new SelectList(db.Computers, "Id", "ComputerName");
  ....

并认为(始终最好使用强类型的辅助函数)

@Html.DropDownListFor(m => m.SoftwareId, Model.SoftwareList, "-- Select --", new { @class = "select2" })

其他一些注意事项。

  • 您应该使用[Display(Name="..")]属性(而不是[DisplayName(..)]
  • 设置LastModified属性时,应考虑使用UCT时间。
  • Id视图中不需要属性的隐藏输入(假设您使用的是默认{controller}/{action}/{id}路由映射)-将其添加到路由值中,并且无论如何将被绑定
  • 除非您特别想要id表单属性,否则可以使用@using(Html.BeginForm()) {
  • 您不需要输入第二个参数LabelFor()-只需Html.LabelFor(m => m.SoftwareId, new { @class = "control-label col-md-2" })[Display]属性中指定它即可

最后,如果您想进一步简化视图,可以考虑EditorTemplates按照本答案中的说明使用自定义或html帮助器,从而可以替换

<div class="form-group">
  @Html.LabelFor(model => model.SoftwareId, new { @class = "control-label col-md-2" })
  <div class="col-md-10">
    @Html.DropDownListFor(m => m.SoftwareId, Model.SoftwareList, "-- Select --", new { @class = "select2" })
    @Html.ValidationMessageFor(model => model.SoftwareId)
  </div>
</div>

与(自定义EditorTemplate

@Html.EditorFor(m => m.SoftwareId, "BootstrapSelect", Model.SoftwareList)

或(自定义HtmlHelper

@Html.BootstrapDropDownFor(m => m.SoftwareId, Model.SoftwareList)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章