Using the Bind attribute on a ViewModel class in ASP.NET MVC - c#

Why might a developer use the Bind attribute on a ViewModel object in an ASP.NET MVC project and can this have a detrimental effect an application?
[Bind(Include = "Id,Name")]
[MetadataType(typeof (MyViewModelValidation))]
public class MyViewModel
{
public string CustomerProductUserName { get; set; }
[Display(Name = "Name")]
public string Name { get; set; }
}
public class MyViewModelValidation
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[Required]
public string Name{ get; set; }
}

First of all, you don't need to create a MetadataType class for a ViewModel. You can use data annotation attributes directly in your ViewModel. MetadataType classes are used for Models automatically generated by EF or other ORMs, so that you can use data annotation attributes without touching the auto-generated code.
The Bind attribute does not have to be used either - unless you want to use Include or Exclude properties of the Bind attribute, to include or exclude properties in your Model in or from binding, respectively.
For example, in the code in your question, only the Id and Name properties will be bound when submitting your Model from your View. Even if you have an input in your View for CustomerProductUserName, when you submit your form, the property will always be null. This can be useful in cases like where you don't want an auto-generated ID field to be included in binding.
Properties excluded from binding are also excluded from validation, because validation is done as part of model binding. Also, you may use the Bind attribute for security reasons; for instance, when you want to make sure nothing but the properties in your model are being posted to the controller.

The purpose of using bind attribute is to prevent attacker from assigning property value while posting of request or control what properties you want to bind.
Let us suppose, you have a class called Member and a create method that saves member. But you do not want user to send a value for MemberType property.
Class Member
{
public int MemberId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MemberType { get; set; }
}
[HttpPost]
Public ActionResult Create(Member member)
{
Save(member);
}
Let's say for now, you are only offering Regular member type which is the default value. You might think that you can prevent the user to send a value for MemberType property by not allowing input for MemberType Property. But when a user posts the member object, an attacker may intercept the request and send the MemberType value in request, as
MemberId=1&FirstName=Chandra&LastName=Malla&MemberType=Premium and save the member as a Premium member. To prevent this, you can decorate Member class with Bind attribute.
[Bind(Include="MemberId,FirstName,LastName")]
Class Member
{
...
or
[Bind(Exclude="MemberType")]
Class Member
{
...
Now if Member object is posted, MemberType property value will not be posted.
If you are using ViewModel, you might not necessarily have to use bind attribute because you can omit MemberType properties in your ViewModel.
Class Member
{
public int MemberId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MemberType { get; set; }
}
Class MemberViewModel
{
public int MemberId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
[HttpPost]
Public ActionResult Create(MemberViewModel memberviewmodel)
{
Save(memberviewmodel);
}
If you do not nicely design your model and/or ViewModel and do not use bind attribute to avoid posting of property you do not want, that might have detrimental effect.

In addition, if you want to prevent refactoring issues when renaming properties from your model you could do something like:
public async Task<ActionResult> Create([Bind(Include = nameof(Foo.Bar1)+","+nameof(Foo.Bar2)+","+nameof(Foo.Bar3))] Foo fooObj)
If you now e.g. rename "Bar1" your Include Bindings will still work.

You can use the Bind attribute to control how a model binder converts a request into an
object. The most common way that you use the Bind attribute is when you exclude an Id property from binding. For example, the Persons database table includes a column named Id
that is an Identity column. Because the value of an Identity column is generated by the
database automatically, you don’t want to bind a form field to this property.
On the other hand, imagine that a property of a model is especially sensitive, which a malicious user could simply append it in a URL when submitting a form. If this were done, the model binder would happily discover and use the data value in the binding process. By Bind attribute you can protect your application from this kind of attack.
Using the Bind attribute could make problem(s) when you, for example, are going to update an entity and the ID is important for you.

Related

c# Webapi and model binding with fluentvalidation

how do I get asp.net webapi to look at the route data and body to bind to a complex object?
Using the following route "api/products/{productid}/manufacturers/{manufacturerId}" I need the productId and manufacturerId to bind to a model, so my controller method is as
public IHttpActionResult Create(CreateProductManufacturerModel
createProductManufacturerModel)
and my model is
public class CreateProductManufacturerModel
{
public int ProductId { get; set; }
public int ManufacturerId { get; set; }
public bool IsDefault { get; set; }
public string ManufacturerCode { get; set; }
public string Description { get; set; }
}
I know I could change my method to be as below, but I am using fluentvalidation to validate the whole createproductmanufacturermodel, this is done automatically (see- http://www.justinsaraceno.com/2014/07/fluentvalidation-with-webapi2/). So the productId and manufacturerId would not be validated correctly as the are set as zero.
public IHttpActionResult Create(int productId, int manufacturerId, CreateProductManufacturerModel
createProductManufacturerModel)
I've have tried a modelbinder but it then does not fire the fluentvalidation automatically. Not too sure if this matters, but the body being posted is in a json format.
Thanks in advance.
Paul
Inherit System.Web.Http.Filters.ActionFilterAttribute.
Override OnActionExecuting()
Extract routing data using actionContext.RequestContext.RouteData.Values
Extract model using actionContext.ActionArguments
Validate and assign routing data to model properties
Decorate your action with the new attribute you created.
If this is a less specific use case, you can use reflection to assign routing data to model properties according to param names.
Can you change your action signature to be:
public IHttpActionResult Create([FromBody]CreateProductManufacturerModel
createProductManufacturerModel){}
and then validate the 2 values you need: createProductManufacturerModel.ProductId and createProductManufacturerModel.ManufacturerId ?

Submitting a model to action that is different from view model's type

I have two models:
public class PersonViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
}
public class DetailViewModel
{
public IEnumerable<string> Titles { get; set; }
public PersonViewModel Person { get; set; }
}
The form is presented with two fields, the first field being the Name, the second field being the a dropdown of Titles (Mr., Mrs. Miss., etc.)
The view for this page is strongly typed to DetailViewModel, and the Save method in the controller accepts a parameter of type PersonViewModel.
Since the view is strongly typed to a type that is different from the form action's parameter type, the names in the HttpRequest do not match what MVC is expecting in the action.
Is it possible to have MVC bind correctly with the model mismatch without having to manually specify form field names? (eg. I still want to use #Html.TextBoxFor(m => m.Person.Name))
For clarification, the form field names that are being submitted are similar to the following:
Person.Name=Matthew&Person.Title=Mr.
Where I need the following (for model binding to work):
Name=Matthew&Title=Mr.
You can use the Prefix property of BindAttribute in the action method
public ActionResult Edit([Bind(Prefix="Person")]PersonViewModel model)
{
}
This essentially strips the Person prefix from the property name while binding

Filter Serialized class properties to reduce WebAPI payload

a C# ASP.NET Webform site using WebAPI
I have a petapoco class that has 50 properties on it, but for certain WebAPI methods I would like to filter what properties are serialized and sent to the client in the HttpResponseMessage (to reduce the payload).
For Example let say I have the following class properties in a class:
ID, FirstName, LastName, Address, City, State, Zip, DOB
I need some WebApi methods to serialize every property, but maybe another method I only want to return
ID, FirstName, LastName
Is there a built in way to handle this?
If not, what's the best way to build out something to handle this?
Edit: I'm looking for a way to do this without modifying the class
You should be able to create ShouldSerialize methods for each property.
Xml serialization - Hide null values
Gives you the ability to dynamically decide which fields get serialized. Don't worry that the link says XML, should work for JSON serialization too.
uses the JsonIgnoreAttribute to exclude a property from serialization.
for example in model.cs:
public class Account
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[JsonIgnore]
public string Address { get; set; }
[JsonIgnore]
public string City { get; set; }
[JsonIgnore]
public string State { get; set; }
.
.
.
}

Binding public fields with ASP.NET MVC as well as public properties?

Obviously, ASP.NET MVC's binding functionality takes care of binding a model's public properties when passing it to a controller, so for instance in the following example, Surname and Email will be bound with their submitted values:
public ActionResult Create(UserModel mdlNewUser) {
// ...
}
// ...
public class UserModel {
public string Firstname;
public string Surname { get; set; }
public string Email { get; set; }
}
However, it doesn't seem to auto-bind public fields such as Firstname in the above example; these will be left untouched. Is there any way to get public fields (and for that matter, any other type of class member) to be automatically bound, or will it only ever bind public properties?
This article seems to imply that it's only public properties because it only ever refers to them all the way through, but it doesn't explicitly seem to say that only public properties will be bound.
That's correct, only public properties will be bound.
Fields cannot be used for binding.

How to "DRY up" C# attributes in Models and ViewModels?

This question was inspired by my struggles with ASP.NET MVC, but I think it applies to other situations as well.
Let's say I have an ORM-generated Model and two ViewModels (one for a "details" view and one for an "edit" view):
Model
public class FooModel // ORM generated
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public int Age { get; set; }
public int CategoryId { get; set; }
}
Display ViewModel
public class FooDisplayViewModel // use for "details" view
{
[DisplayName("ID Number")]
public int Id { get; set; }
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("Last Name")]
public string LastName { get; set; }
[DisplayName("Email Address")]
[DataType("EmailAddress")]
public string EmailAddress { get; set; }
public int Age { get; set; }
[DisplayName("Category")]
public string CategoryName { get; set; }
}
Edit ViewModel
public class FooEditViewModel // use for "edit" view
{
[DisplayName("First Name")] // not DRY
public string FirstName { get; set; }
[DisplayName("Last Name")] // not DRY
public string LastName { get; set; }
[DisplayName("Email Address")] // not DRY
[DataType("EmailAddress")] // not DRY
public string EmailAddress { get; set; }
public int Age { get; set; }
[DisplayName("Category")] // not DRY
public SelectList Categories { get; set; }
}
Note that the attributes on the ViewModels are not DRY--a lot of information is repeated. Now imagine this scenario multiplied by 10 or 100, and you can see that it can quickly become quite tedious and error prone to ensure consistency across ViewModels (and therefore across Views).
How can I "DRY up" this code?
Before you answer, "Just put all the attributes on FooModel," I've tried that, but it didn't work because I need to keep my ViewModels "flat". In other words, I can't just compose each ViewModel with a Model--I need my ViewModel to have only the properties (and attributes) that should be consumed by the View, and the View can't burrow into sub-properties to get at the values.
Update
LukLed's answer suggests using inheritance. This definitely reduces the amount of non-DRY code, but it doesn't eliminate it. Note that, in my example above, the DisplayName attribute for the Category property would need to be written twice because the data type of the property is different between the display and edit ViewModels. This isn't going to be a big deal on a small scale, but as the size and complexity of a project scales up (imagine a lot more properties, more attributes per property, more views per model), there is still the potentially for "repeating yourself" a fair amount. Perhaps I'm taking DRY too far here, but I'd still rather have all my "friendly names", data types, validation rules, etc. typed out only once.
I'll assume that your doing this to take advantage of the HtmlHelpers EditorFor and DisplayFor and don't want the overhead of ceremoniously declaring the same thing 4000 times throughout the application.
The easiest way to DRY this up is to implement your own ModelMetadataProvider. The ModelMetadataProvider is what is reading those attributes and presenting them to the template helpers. MVC2 already provides a DataAnnotationsModelMetadataProvider implementation to get things going so inheriting from that makes things really easy.
To get you started here is a simple example that breaks apart camelcased property names into spaces, FirstName => First Name :
public class ConventionModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
HumanizePropertyNamesAsDisplayName(metadata);
if (metadata.DisplayName.ToUpper() == "ID")
metadata.DisplayName = "Id Number";
return metadata;
}
private void HumanizePropertyNamesAsDisplayName(ModelMetadata metadata)
{
metadata.DisplayName = HumanizeCamel((metadata.DisplayName ?? metadata.PropertyName));
}
public static string HumanizeCamel(string camelCasedString)
{
if (camelCasedString == null)
return "";
StringBuilder sb = new StringBuilder();
char last = char.MinValue;
foreach (char c in camelCasedString)
{
if (char.IsLower(last) && char.IsUpper(c))
{
sb.Append(' ');
}
sb.Append(c);
last = c;
}
return sb.ToString();
}
}
Then all you have to do is register it like adding your own custom ViewEngine or ControllerFactory inside of Global.asax's Application Start:
ModelMetadataProviders.Current = new ConventionModelMetadataProvider();
Now just to show you I'm not cheating this is the view model I'm using to get the same HtmlHelper.*.For experience as your decorated ViewModel:
public class FooDisplayViewModel // use for "details" view
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[DataType("EmailAddress")]
public string EmailAddress { get; set; }
public int Age { get; set; }
[DisplayName("Category")]
public string CategoryName { get; set; }
}
Declare BaseModel, inherit and add another properties:
public class BaseFooViewModel
{
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("Last Name")]
public string LastName { get; set; }
[DisplayName("Email Address")]
[DataType("EmailAddress")]
public string EmailAddress { get; set; }
}
public class FooDisplayViewModel : BaseFooViewModel
{
[DisplayName("ID Number")]
public int Id { get; set; }
}
public class FooEditViewModel : BaseFooViewModel
EDIT
About categories. Shouldn't edit view model have public string CategoryName { get; set; } and public List<string> Categories { get; set; } instead of SelectList? This way you can place public string CategoryName { get; set; } in base class and keep DRY. Edit view enhances class by adding List<string>.
As LukLed said you could create a base class that the View and Edit models derive from, or you could also just derive one view model from the other. In many apps the Edit model is basically the same as View plus some additional stuff (like select lists), so it might make sense to derive the Edit model from the View model.
Or, if you're worried about "class explosion", you could use the same view model for both and pass the additional stuff (like SelectLists) through ViewData. I don't recommend this approach because I think it's confusing to pass some state via the Model and other state via ViewData, but it's an option.
Another option would be to just embrace the separate models. I'm all about keeping logic DRY, but I'm less worried about a few redundant properties in my DTOs (especially on projects using code generation to generate 90% of the view models for me).
First thing i notice - you got 2 view models. See my answer here for details on this.
Other things that springs in mind are already mentioned (classic approach to apply DRY - inheritance and conventions).
I guess i was too vague. My idea is to create view model per domain model and then - combine them at view models that are per specific view. In your case: =>
public class FooViewModel {
strange attributes everywhere tralalala
firstname,lastname,bar,fizz,buzz
}
public class FooDetailsViewModel {
public FooViewModel Foo {get;set;}
some additional bull**** if needed
}
public class FooEditViewModel {
public FooViewModel Foo {get;set;}
some additional bull**** if needed
}
That allows us to create more complex view models (that are per view) too =>
public class ComplexViewModel {
public PaginationInfo Pagination {get;set;}
public FooViewModel Foo {get;set;}
public BarViewModel Bar {get;set;}
public HttpContext lol {get;set;}
}
You might find useful this question of mine.
hmm... turns out i actually did suggest to create 3 view models. Anyway, that code snippet kind a reflects my approach.
Another tip - i would go with filter & convention (e.g. by type) based mechanism that fills viewdata with necessary selectList (mvc framework can automagically bind selectList from viewData by name or something).
And another tip - if you use AutoMapper for managing your view model, it has nice feature - it can flatten object graph. Therefore - you can create view model (which is per view) that directly has props of view model (which is per domain model) whatever how much deep you want to go (Haack said it's fine).
These display names (the values) could perhaps be displayed in another static class with a lot of const fields. Wouldn't save you having many instances of DisplayNameAttribute but it would make a name change quick and easy to make. Obviously this is isn't helpful for other meta attributes.
If I told my team they would have to create a new model for every little permutation of the same data (and subsequently write automapper definitions for them) they'd revolt and lynch me. I'd rather model metadata that was, too some degree use aware. For example making a properties required attribute only take effect in an "Add" (Model == null) scenario. Particularly as I wouldn't even write two views to handle add/edit. I would have one view to handle the both of them and if I started having different model classes I'd get into trouble with my parent class declaration.. the ...ViewPage bit.

Categories

Resources