automapper dto to viewmodel - viewmodel

How can I map my dto to my ViewModel, knowing the following :
My dto:
public class SomeClass
{
public int myProperty{get; set;}
}
my viewModel:
public class MyViewModel
{
public SomeClass theDto {get; set;}
public int someExtraProperty
}
So, my ViewModel contains my dto + other properties. How can I easily map the dto object ?

actually the following seems to work !
AutoMapper.Mapper.CreateMap<SomeClass, MyViewModel>().ForMember(d => d.theDto, s => s.MapFrom(src => src));

Related

fluentvalidation for partial class

I have a customer class like this:
[Validator(typeof(CustomerValidator))]
public partial class Customer {
public string FirstName { get; set; }
public string LastName { get; set; }
}
And my Validation class is:
public class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(x => x.FirstName)
.NotEmpty()
.WithMessage("FirstName is required."));
RuleFor(x => x.LastName)
.NotEmpty()
.WithMessage("LastName is required."));
}
}
Everything works fine, the code did validate fields.
I planned to extend the Customer class and add Email field. I cannot edit my old code file. I create new partial Customer class and new validation for Email field.
I can create partial customer class like this:
public partial class Customer {
public string Email { get; set; }
}
But I don't know how to validate this field via another class. The code below is what i expected but it I dont know how to bind it in the Customer Email field:
public class CustomerEmailValidator : AbstractValidator<Customer>
{
public CustomerEmailValidator()
{
RuleFor(x => x.Email)
.EmailAddress()
.WithMessage("Email address is not valid."));
}
}
All helps are appreciated.
Thanks in advance.
Put [Validator(typeof(CustomerValidator))] annotation on the partial class as well.

Can you add additonal metadata via data annotations to a base model property from a child model?

I am currently working on a asp.net mvc 3 project, where I'm using a custom attribute called [ColumnHeading] to decorate the properties I want to display in a grid. I have a base model that has a couple of properties that sometimes need to be displayed in the grid of the child class.
Example:
public class BaseClass
{
public String Status { get; set; }
}
public class ChildClass : BaseClass
{
[Display(Name="Property 1")]
[ColumnHeading]
public String Property1 { get; set; }
[Display(Name = "Property 2")]
[ColumnHeading]
public String Property2 { get; set; }
}
I don't know if this has been asked before (search around for about 3 hours) and if this even possible, but can you add the [ColumnHeading] attribute to the base class property in the child class e.g.?
public class ChildClass : BaseClass
{
public ChildClass()
{
// Fictional method to add attribute to property
AddAdditionalMetaData(Status, [ColumnHeading]);
}
...
}
I know that you can make the base class property virtual or make a view model of the base and child class, but the project has 40+ models that inherit from the base class, and about 30 of the child classes needs to display this base class property, so view models doensn't really make it worthwhile for one property extra.
Secondly i have to override the property several times which ends in endless repetative which i dont like, but if this is the only way. I'll do it.
Any help will be appreciated.
[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public class ColumnHeadingAttribute
{
...
See the Inherited property on the AttributeUsageAttribute. If you have this on your custom attribute, it will be inherited to child classes. You can then create an intermediate base viewmodel between the base viewmodel and the child viewmodels.
public class BaseClass
{
public virtual string Status { get; set; }
}
public abstract class IntermediateClass : BaseClass
{
[ColumnHeading]
public override string Status { get; set; }
}
public class ChildClass : IntermediateClass
{
public ChildClass()
{
// Status will inherit the ColumnHeading attribute from IntermediateClass
}
...
}

Html.EditorFor method for interface attributes

I'm a beginner ASP.NET MVC 3 web-developer and have this problem:
There are several view models, that have similar logic and I've come to idea to have one common EditorTemplate for them to be rendered by Html.EditorFor.
The template is named "ExistOrCreateNewInput.cshtml" and is strongly-typed with IExistOrCreateNewInput interface class:
public interface IExistOrCreateNewInput
{
int? existEntId { get; set; }
IUnapprovedNewEntityCreateInput createInput { get; set; }
}
Template's content is something like:
#model IExistOrCreateNewInput
<h2>Add or choose</h2>
#* here put some common js code *#
Html.EditorFor(o => o.existEntId)
Html.EditorFor(o => o.createInput)
Suppose I have some sort of models that implement this interface, for example:
public class FirstModelInput : IExistOrCreateNewInput
{
[Display(Name="First")]
[UIHint("Lookup")]
public int? existEntId {get; set;}
[UIHint("PaperCreateInput")]
public PaperCreateInput paperCreateInput {get; set;}
public IUnapprovedNewEntityCreateInput createInput
{
get
{
return paperCreateInput;
}
set { }
}
}
public class SecondModelInput : IExistOrCreateNewInput
{
[Display(Name="Second")]
[UIHint("Lookup")]
public int? existEntId {get; set;}
[UIHint("ThesisCreateInput")]
public ThesisCreateInput thesisCreateInput {get; set;}
public IUnapprovedNewEntityCreateInput createInput
{
get
{
return thesisCreateInput;
}
set { }
}
}
public class ThirdModelInput : IExistOrCreateNewInput
{
...
}
Where PaperCreateInput and ThesisCreateInput classes implement IUnapprovedNewEntityCreateInput interface.
So, I want my view model
public class SomeGlobalViewModel
{
[Required]
string name {get; set;}
[UIHint("ExistOrCreateNewInput")]
FirstModelInput firstModel {get; set;}
}
to render correctly the attribute "firstModel" with Html.EditorFor(o => o.firstModel) method.
Now I know that EditorFor method is dealing with Metadata, so probably my question should be like "how can I pass metadata of attributes to base interface attributes". Correct me, if I'm wrong.
Anyway, I need those helper methods
Html.EditorFor(o => o.existEntId)
Html.EditorFor(o => o.createInput)
in my editor template (strongly-typed with interface) to render my Models' attributes as I declared them in implementing classes:
[UIHint("Lookup")]
public int? existEntId {get; set;}
[UIHint("PaperCreateInput")]
public PaperCreateInput createInput {get; set;}
Thanks in advance.
Sorry for my bad English.

How to update a property of an abstract with an inheriting/using a subblass in MVC

I have an abstract class
public abstract class Member
{
public string ID { get; set; }
public string Username { get; set; }
public int MemberType { get; set; }
public abstract string MemberName { get; set; }
public int Status { get; set; }
}
public class Person : Member
{
public string LastName { get; set; }
public string FirstName{ get; set; }
}
public class Business : Member
{
public string BusinessName { get; set; }
public string TaxNo { get; set; }
}
The class was mapped using fluent API,
Now, is there a way to update the "Status" property from the view(having Member model) without using or going to a subclass (Person/Business)?
I just tried it, but it says "Cannot create an abstract class.", when submitting the page.
Or there is a correct way to do this?
Thanks
Not in EF. You have to instantiate an object to work with EF, and you can't instantiate an abstract class.
You could make the class not be abstract. Or you could use a stored proc to update the field, or some direct sql.
It sounds like your problem is that your action method has an abstract type as a parameter, which the default model binder can't do anything with. If you are dead set on using the same view for two different classes, you may need to implement your own model binder to inspect in the incoming request and decide which type, Person or Business, to instantiate.
Check out this link for more information on creating a custom model binder:
http://odetocode.com/blogs/scott/archive/2009/05/05/iterating-on-an-asp-net-mvc-model-binder.aspx
This seems like a similar problem to the one I've answered previously here:
ASP.NET MVC 3: DefaultModelBinder with inheritance/polymorphism

Weird data binding behavior in ASP.NET MVC3?

I have the following domain objects:
public class Foo
{
public Id {get; set;}
**public BarId {get; set;}**
public virtual Bar {get; set;}
public string Name {get; set;}
}
public class Bar
{
public Id {get; set;}
public string Name {get; set;}
}
The view model used by the view looks like this:
public class FooEditorModel
{
public Foo {set; get;}
public SelectList Bars { get; set; }
}
The view looks like this:
#model FooEditorModel
#Html.ValidationSummary( true )
#Html.HiddenFor( model => model.Foo.Id )
#Html.LabelFor( model => model.Foo.BarId, "Bar" )
#Html.DropDownListFor( model => model.Foo.BarId, Model.Bars )
#Html.ValidationMessageFor( model => model.Foo.BarId )
The controller looks like this:
[HttpPost]
public virtual ActionResult Save( FooEditorModel model )
{
if ( ModelState.IsValid )
{
Foo foo = MakeAModel( model );
FooRepository.Save( foo );
}
}
Foo MakeAModel( model )
{
Foo foo = MakeAFoo();
**foo.BarId = model.Foo.BarId;**
return foo;
}
Quite standard code, a bit simplified.
The problem is that if I use a Bar in Foo, instead of BarId, the ModelState is not valid (because of Bar.Name).
I find it very poorly designed to be forced to have both a child Id and a reference to the child in the root object.
Is this the only way for a data binding to work in MS MVC 3?

Resources