在MVC3中放置到模型中的对象的顺序是什么,以及如何控制它

时间:2012-04-04 19:35:46

标签: asp.net-mvc-3

我有一个模型从我的视图成功传回,除了我想要一个ID值是第一个绑定到模型的东西,所以它可以从db填充一些信息。传回的信息如下

SetupID:91c16e34-cf7d-e111-9b66-d067e53b2ed6
SwayBarLinkLengthLF:
SwayBarLinkLengthRF:
.....way more information....

我的行动如下

[HttpPostAttribute]
public ActionResult SaveSetup(SetupAggregate setup)
{
   setup.SaveSetup();
   return null;
}

我希望SetupID是第一个在空设置对象上设置的属性,但它看起来像是按字母顺序首先设置的第一个属性。

1 个答案:

答案 0 :(得分:0)

在我看来,你真的需要使用2个独立的“模型” - 你的ViewModel,这是你的MVC项目中的东西,并呈现给你的视图。并且是业务逻辑层中的第二个EntityModel。这是标准的“企业”编程设计。它可以让您更好地控制数据。这个想法是这样的。

UI Assembly(MVC项目)

ViewModel定义

public class MyModel {
    public int ID { get; set; }
    .... // bunch of other properties
}

控制器

public class InterestingController : Controller {

    public ActionResult CreateNewWidget() {
        var model = new MyModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult CreateNewWidget(MyModel model) {
        if(ModelState.IsValid) {
            // your ctor can define the order of your properties being sent in and you can set the entity values in the ctor body however you choose to. Note never SET an ID/Primary key on a Create, let the DB handle that. If you need to return the new Key value, get it from the insert proc method in your DAL and return it up the stack
            var entityModel = new EntityFromBLL(model.Name, model.OtherProperty, ... etc);
            entityModel.Save(User.Identity.Name); // your save method should always capture WHO is doing the action
        }
        return View(model);
    }

    public ActionResult UpdateExistingWidget(int id) {
        var entityModel = new EntityFromBLL(id); // get the existing entity from the DB
        var model = new MyModel(entityModel.ID, entityModel.Name, ... etc); // populate your ViewModel with your EntityModel data in the ViewModel ctor - note remember to also create a parameterless default ctor in your ViewModel as well anytime you create a ctor in a ViewModel that accepts parameters
        return View(model);
    }

    [HttpPost]
    public ActionResult UpdateExistingWidget(MyModel model) {
        if(ModelState.IsValid) {
            var entityModel = new EntityFromBLL(model.ID); // always pull back your original data from the DB, in case you deal with concurrency issues
            // now go thru and update the EntityModel with your new ViewModel data
           entityModel.Name = model.Name;
           //... etc set all the rest of the properties
           // then call the save
           entityModel.Save(User.Identity.Name);
        }
        return View(model)
    }
}

您的实体模型应该使用私有字段,公共属性,接受插入的所有必填字段(减去主键)的ctor,接受主键的ctor然后可以调用内部加载方法来定义静态返回填充的对象。业务规则和属性验证以及单个Save方法。在设置了所有属性后,Save方法应检查IsDirty位,并调用相应的Insert或Update方法..这些方法又应调用DAL传递DTO