0

I have following code and the problem is that values I am sending from the form are stored in additional class in model and after submit the values are NULL in controller model.

Controller:

public ActionResult Territory(TerritoryVM m)
    {
        if (ModelState.IsValid)
        {
            !!! m.TerritoryFormItem IS NULL !!!
        }
    }

Model:

public class TerritoryVM
{
    public TerritoryVM()
    {
    }

    public TerritoryFormItem TerritoryFormItem;
}

Class used in model:

public class TerritoryFormItem
{
    [Required, DisplayName("Territory Name")]
    public string Name { get; set; }        
}

View:

@Html.LabelFor(m => m.TerritoryFormItem.Name)
@Html.TextBoxFor(m => m.TerritoryFormItem.Name, new { @class = "form-control" })

Any Idea ?

Muflix
  • 6,192
  • 17
  • 77
  • 153
  • 2
    Because `TerritoryFormItem` is a field, not a property and the `DefaultModelBinder` only binds properties. Change it to `public TerritoryFormItem TerritoryFormItem { get; set; }` –  May 19 '16 at 13:26
  • 1
    Seriously, you accepted that answer? –  May 19 '16 at 13:49
  • Stephen: yes because in the answer was "link" to your comment which solved my problem, but I cannot accept comment, only answer.. anyway thank you a lot. – Muflix May 20 '16 at 08:48
  • Please do not accept bad answers. It just misleads other user who come across this. The question is marked as duplicate so there is no need to accept anything (and I deleted the reference to my name - I wont be associated with that nonsense) –  May 20 '16 at 10:40

1 Answers1

0

Model binding is wrong, which means data type doesn't match.

The use of ViewModel is weird in your code. Should it be a similar class to Model class, rather than having cascading class in ViewModel...

I am sure you can do this, but it's not straight forward at all.

CodeFarmer
  • 2,644
  • 1
  • 23
  • 32