How to bind multiple form values ​​to a single property?

I have 3 inputs named: Field_Day, Field_Month, Field_Year.

And a model that looks like this:

public class Model
{
  public string Field { get; set; }
}

      

How do I bind these 3 form values ​​to my Field property ("10/10/2015")?

Edit:

Most of the answers suggested changing my view model. This is not possible because my model is a meta model.

public class MetaModel
{
  public string[] FieldValues { get; set; } // Select Multiple inputs can have more than one value
  public string ControlType { get; set; }
  ...
}

      

+3


source to share


2 answers


In the view model, I do something like the following:

public int Day { get; set; }
public int Month { get; set; }
public int Year { get; set; }

public DateTime Field
{
    get { return new DateTime(Year, Month, Day); }
    set
    {
        Day = value.Day;
        Month = value.Month;
        Year = value.Year;
    }
}

      



An entity representing this will have a property Field

. So, in your form, you can use properties Day

, Month

and Year

, and then when you go back to your entity, you set the Field

property Field

to a property in your view model that is automatically populated from what was posted.

I also recommend using DateTime here instead of string. Not only does it make it easy to convert back and forth without having to do a bunch of string parsing, but then you can represent the date in whatever format it needs to be, not just one static format of your string.

+2


source


You will want to create another class and then name your input elements accordingly, either with razor helpers or manually

FROM#

public class ViewModel
{
 public Field Field { get; set; }
}

public class Field
{
 public string Day { get; set; }
 public string Month{ get; set; }
 public string Year{ get; set; }
} 

      



.cshtml

@model ViewModel

<form>
 <div>Field Day <input name="Field.Day" /></div>
 <div>Field Month <input name="Field.Month" /></div>
 <div>Field Year <input name="Field.Year" /></div>
</form>

      

The name attribute is what the asp.net mvc linker uses to populate the view model. This is why they have a dotted extension.

+1


source







All Articles