0

I know there are a couple of options to exclude/include some parameters in a modelview like using bind or using interfaces. However I have some problems when I am trying to implement nested IEnumerable variables. For example:

public class TestViewModel()
{
    public int Id { get; set; }
    public IEnumerable<Organisation> KPI { get; set; }
}

public class Organisation
{  
    public string Id { get; set; }
    public string Name {get; set;}
    public DateTime StartDate {get; set;}
    public IEnumerable<Regiod> CategoryValues { get; set;  }
}

public class Region
{
   public System.Guid Id { get; set; }
   public System.Int32 RegionId { get; set; }
   public int Value { get; set; }
   public System.String RegionName { get; set; }
}

[HttpGet]
public ActionResult edit(int id)
{
  var model = new TestViewModel();
  // Do something to populate the model
  view(model)
}

In the view page (razor) all fields are disabled or hidden, except field Value in Region class and StartDate in Organization. My action Code is something like:

[HttpPost]
public ActionResult edit(TestViewModel model)
{
  // Do something to populate the model
}

Everything works fine, unless somebody uses for example fiddler to set other disabled or hidden values, so those fields will be updated.

What I am after is to update just enabled fields and exclude the rest even somebody tries to set a value for them.

I tried bind[Exclude and Include], but my problem is I can bind 2 values from different classes. I tried UpdateModel(model, include) and it didn't work.

Any advice would be appreciated.

Arash EM
  • 370
  • 6
  • 16
  • The best way to prevent over posting is, create a view model which has only those properties needed for the view. Take a look at [this](http://stackoverflow.com/questions/34125780/how-to-update-model-in-asp-net-mvc-6/34126048#34126048) and [this](http://stackoverflow.com/questions/34260334/mvc-6-bind-attribute-disappears/34260397#34260397) – Shyju Jan 13 '16 at 01:41
  • You should be using view models for `Organisation` and `Region` as well. When you submit, initialize you data model(s) and map only those properties from the view models you want. –  Jan 13 '16 at 01:43
  • Thanks guys, so if I change my edit action method to something like: public ActionResult edit(int id, Organisation model1, Region model2), it should work? – Arash EM Jan 13 '16 at 02:02
  • I just created a view model which has only those properties needed and then mapped them in the edit action method and it worked fine. Thanks again guys – Arash EM Jan 13 '16 at 02:41

0 Answers0