视图模型虚拟财产和下拉列表 [英] View Model virtual properties and drop down lists

查看:139
本文介绍了视图模型虚拟财产和下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法掌握正确的方法来创建视图模型,并使用实体框架回保存信息到数据库中,我似乎无法找到我要找的,所以请原谅我,如果我的信息忽视它。



我碰到这个帖子的这里,他似乎被问同样的问题,但没有得到答案。



我的主要问题是,



进行编辑,如果我有一个产品型号型号具有保修模型的关系,我应该使用虚拟财产担保视图模型或我应该使用 INT WarrantyId



如果我应该使用虚拟财产,为什么不这段代码保存在保修是否正确?



我需要明确的标志或填充保修对于更新?



请不这样做填充我的编辑视图,然后选择列表中按预期。



我(简体)代码的设置如下:



模型:

 公众诠释ModelId {搞定;组; } 

公众诠释ModelNumber {搞定;组; }

公共虚拟保修保修{搞定;设置;}

查看产品型号:

 公众诠释ModelId {搞定;组; } 

[必需(的ErrorMessage =所需的型号)]
[StringLength(25的ErrorMessage =必须在25个字符)]
[显示(名称= 型号)]
公共字符串ModelNumber {搞定;组; }

//相关的对象和属性necesary
公共虚拟保修保修{搞定;组; }

公开的IEnumerable< SelectListItem> WarrantySelectListItems {搞定;组; }



控制器(GET):

 公众的ActionResult编辑(INT?ID)
{
//检查ID
如果(ID == NULL)
{
返回新HttpStatusCodeResult(HttpStatusCode.BadRequest);
}

//获取模式,并确保该对象填充
VAR模型= _modelService.GetModel(id.Value);
如果(型号== NULL)
{
返回HttpNotFound();
}

//通过我们的实体(DB)模式,我们的视图模型
变种editModelModel =新EditModelModel();
editModelModel.InjectFrom(模型);

//保修选择列表中的
editModelModel.WarrantySelectListItems = WarrantySelectList(editModelModel.Warranty.WarrantyId);

//选择多选列表
editModelModel.OptionSelectListItems = OptionSelectList();

返回查看(editModelModel);
}



控制器(POST)(工作正在进行中):

  [HttpPost] 
[ValidateAntiForgeryToken]
公众的ActionResult编辑(EditModelModel editModelModel)
{
如果( !ModelState.IsValid)
{
返回查看(editModelModel);
}

变种modelEntity =新模式();
modelEntity.InjectFrom(editModelModel);

_modelService.Update(modelEntity);
_unitOfWork.Save();

返回RedirectToAction(「指数」);
}

查看(简体):

 < DIV CLASS =表单组> 
@ Html.Label(保证,新{@class =控制标签COL-MD-2})
< DIV CLASS =COL-MD-10>
@ Html.DropDownListFor(X => x.Warranty.WarrantyId,Model.WarrantySelectListItems - 选择 - )
@ Html.ValidationMessageFor(型号=> model.Warranty.WarrantyId)
< / DIV>
< / DIV>



同样,我只是想知道设置这些的ViewModels和模式,以便正确的/最佳方式EF是做尽可能多的工作尽可能的。 我觉得如果我要创建一个 WarrantyId 字段,我做错了什么,但也许事实并非如此。

提前

感谢。任何有识之士/帮助是极大的赞赏。


解决方案

有关编辑的目的,如果我有一个产品型号模型具有
保修模型的关系,我应该使用虚拟财产
保修视图模型或我应该使用INT WarrantyId?




您不要使用虚拟为关键字的财产你的视图模型,因为视图模型无关实体框架。
之所以使用虚拟关键字,允许在实体框架延迟加载。在你的情况,如果您添加虚拟关键字为
在产品POCO类的保修导航属性,您可以访问担保财产象下面这样:

  Model.Warranty.WarrantyId 

和它没有保存保修信息到你的数据库的原因是因为你需要来定义产品类中的保修外键属性。



在你的情况,如果你使用的代码第一种方法和产品是你的POCO类,只要保持它只是象下面这样:

 公共类产品
{
公众诠释ModelId {搞定;组; }
公众诠释ModelNumber {搞定;组; }
公众诠释WarrantyId {获取;集;}

[ForeignKey的(WarrantyId)]
公共虚拟保修保修{搞定;组; }
}



那么你的视图模型:

 公共类MyViewModel 
{
公共产品产品{搞定;组; }
公开的IEnumerable< SelectListItem> WarrantySelectListItems {搞定;组; }
}



最后,你的看法

  @model MyViewModel 

@ Html.DropDownList(Product.Warranty.WarrantyId,Model.WarrantySelectListItems - 选择 - )
@ Html.ValidationMessageFor(Product.Warranty.WarrantyId)

科西嘉,你需要改变你的操作方法,以满足视图模型。


I'm having trouble grasping the proper way to create view models and save that info back to the database using Entity Framework, and I can't seem to find the info I'm looking for, so please forgive me if I have overlooked it.

I came across this post here and he seems to be asking the same question but doesn't get an answer.

My main questions are,

For editing purposes, If I have a ProductModel model that has a Warranty model relationship, should I be using virtual property Warranty in the view model or should I be using int WarrantyId?

If I should be using a virtual property, why doesn't this code save the Warranty properly?

Do I need to explicitly flag or populate the Warranty for update?

Please not this does populate my edit view and select lists as intended.

My (simplified) code is setup as follows:

Model:

    public int ModelId{ get; set; }

    public int ModelNumber { get; set; }

    public virtual Warranty Warranty { get; set;}

View Model:

    public int ModelId { get; set; }

    [Required(ErrorMessage = "Model Number required")]
    [StringLength(25, ErrorMessage = "Must be under 25 characters")]
    [Display(Name="Model Number")]
    public string ModelNumber { get; set; }

    //related objects and necesary properties
    public virtual Warranty Warranty { get; set; }

    public IEnumerable<SelectListItem> WarrantySelectListItems { get; set; }

Controller (GET):

public ActionResult Edit(int? id)
    {
        //check the id
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        //get the model and make sure the object is populated
        var model = _modelService.GetModel(id.Value);
        if (model == null)
        {
            return HttpNotFound();
        }

        //pass our entity (db) model to our view model
        var editModelModel = new EditModelModel();
        editModelModel.InjectFrom(model);

        //warranty select list
        editModelModel.WarrantySelectListItems = WarrantySelectList(editModelModel.Warranty.WarrantyId);

        //option multi select list
        editModelModel.OptionSelectListItems = OptionSelectList();

        return View(editModelModel);
    }

Controller (POST) (work in progress):

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(EditModelModel editModelModel)
    {
        if (!ModelState.IsValid)
        {
            return View(editModelModel);
        }

        var modelEntity = new Model();
        modelEntity.InjectFrom(editModelModel);

        _modelService.Update(modelEntity);
        _unitOfWork.Save();

        return RedirectToAction("Index");
    }

View (simplified):

<div class="form-group">
        @Html.Label("Warranty", new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(x => x.Warranty.WarrantyId, Model.WarrantySelectListItems, "--Select--")
            @Html.ValidationMessageFor(model => model.Warranty.WarrantyId)
        </div>
    </div>

Again, I just want to know the proper/best way to set up these viewmodels and models so the EF is doing as much of the work as possible. I feel like if I have to create a WarrantyId field, I'm doing something wrong, but maybe that isn't the case.

Thanks in advance. Any insight/help is greatly appreciated.

解决方案

For editing purposes, If I have a ProductModel model that has a Warranty model relationship, should I be using virtual property Warranty in the view model or should I be using int WarrantyId?

You don't use virtual keyword for the property of your ViewModel, because the ViewModel has nothing to do with Entity Framework. The reason to use the virtual keyword is to allow lazy loading in Entity Framework. In your case, if you add the virtual keyword for the Warranty navigation property in the Product POCO class, you can access the Warranty property like below:

Model.Warranty.WarrantyId

And the reason it didn't save the Warranty information into your Database is because you need to define a Warranty foreign key property in the Product class.

In your case, if you're using code first approach and Product is your POCO class, just keep it simply like below:

    public class Product
    {
        public int ModelId { get; set; }
        public int ModelNumber { get; set; }
        public int WarrantyId {get;set;}

        [ForeignKey("WarrantyId ")]
        public virtual Warranty Warranty { get; set; }
    }

Then your ViewModel :

    public class MyViewModel 
    {
        public Product Product { get; set; }
        public IEnumerable<SelectListItem> WarrantySelectListItems { get; set; }
    }

Finally your view

  @model MyViewModel

  @Html.DropDownList("Product.Warranty.WarrantyId", Model.WarrantySelectListItems, "--Select--")
  @Html.ValidationMessageFor("Product.Warranty.WarrantyId")

Of corse, you need to change your action methods to meet the ViewModel.

这篇关于视图模型虚拟财产和下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆