Exclude model binding properties using interfaces

Here is an example that I raised here: http://aspalliance.com/1776_ASPNET_MVC_Beta_Released.5

public ActionResult Save(int id)
{
 Person person = GetPersonFromDatabase(id);
 try
 {
  UpdateMode<IPersonFormBindable>(person)
  SavePersonToDatabase(person);

  return RedirectToAction("Browse");
 }
 catch
 {
  return View(person)
 }
}

interface IPersonFormBindable
{
 string Name  {get; set;}
 int Age   {get; set;}
 string Email {get; set;}
}

public class Person : IBindable
{
 public string Name   {get; set;}
 public int Age    {get; set;}
 public string Email {get; set;}
 public Decimal? Salary  {get; set;}
}

This will not display the values ​​in the Salary property, but will perform its validation attributes, which are not expected when you perform the standard [Bind (Exclude = "Salary")]

[Bind(Exclude="Salary")]
public class Person
{
 public string Name  {get; set;}
 public int Age   {get; set;}
 public stiring Email {get; set;}
 public Decimal? Salary  {get; set;}
}

How can I implement [Bind (Exclude = "Property")] using this interface template?

+3
source share
1 answer

: , . , : , :

public class PersonViewModel
{
    public string Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

:

public ActionResult Save(PersonViewModel person)
{
    _repository.SavePersonToDatabase(person);
    return RedirectToAction("Browse");

    // Notice how I've explicitly dropped the try/catch,
    // you weren't doing anything meaningful with the exception anyways.
    // I would simply leave the exception propagate. If there 
    // a problem with the database it would be better to redirect 
    // the user to a 500.htm page telling him that something went wrong.
}

, , . , . , . , , . . AutoMapper .

, : , . Include, Exclude , , - - Exclude. Include, .

+2

Source: https://habr.com/ru/post/1780569/


All Articles