How do you ignore/persist values in MVC when your

2019-04-28 14:35发布

I have a site where I'm using fluentNhibernate and Asp.net MVC. I have an Edit view that allows user to edit 8 of the 10 properties for that record (object). When you submit the form and the Model binds, the two un-editable fields come back in the view-model as Empty strings or as default DateTime values depending on the type of property.

Because I'm also using AutoMapper to map my view-model to my Domain Entity, I cannot just load a fresh copy of my object from the database and manually set the 2 missing properties. Whats the best way to persist those fields that I don't want edited?

One way that does work is to persist the values in hidden Input fields on my View. That works but feels gross. I appreciate any recommendations. Is there a way in my AutoMapper to configure this desired functionality?

UPDATE: Ok, So I guess I'm not trying to ignore the fields, I'm trying to make sure that I don't persist null or empty string values. Ignoring the fields in AutoMapper does just that, they get ignored and are null when I attempt to map them before Saved to my repository.

3条回答
淡お忘
2楼-- · 2019-04-28 14:42

You can tell Automapper to ignore the 2 properties:

Mapper.CreateMap<Source, Destination>()
.ForMember(dest => dest.SomeValuefff, opt => opt.Ignore());

Possible related question.

查看更多
ら.Afraid
3楼-- · 2019-04-28 14:49

The asp.net mvc DefaultModelBinder is extensible, and you can override it to create your own binding schema. But this will involve more work than two "hidden Input fields", which , in my point of view, is not that gross.

查看更多
劫难
4楼-- · 2019-04-28 14:58

Can you use the AutoMapper.Map overload that also accepts TEntity?!

entity = Mapper.Map(viewmodel, entity);

As long as you do not have the properties on your viewmodel, it won't change the values on your entity. It takes the entity being passed in and applies only the properties from the viewmodel back to the entity.

查看更多
登录 后发表回答