asp.net-mvcmodel-view-controllerasp.net-mvc-2

Model Binding to view in MVC


I am a beginner to MVC and would like to know how I can set by binded model vaule back for viewing. Here is the example.

public class DataTypes
{
    public Guid ItemID { get; set; }
    [Required()]
    public string Name { get; set; }
    [Required()]
    public string Status { get; set; }
    [Required()]
    public DataModel DataModel { get; set; } // This is for Binding
}
public class DataModel
{
    public string Activity { get; set; }
    public DateTime ?DateTime { get; set; }        
}

With the above model class, I am sucessfully able to bind data from UI to backend but the problem is that how I can retrun the same data to UI using the above. I tried the below code but when it comes to setting the vaules for Binded class (DataModel)

        this.dataType.ItemID = // Guid from stored vaule in DataBase
        this.dataType.Name = // Name from stored vaule in DataBase
        this.dataType.Status = // Status from stored vaule in DataBase

                        // Set the activity to UI - ERROR.....!!!!!!
                        // Error was NullReferenceException unhandled
        this.dataType.DataModel.Activity = // Activity from stored vaule in DataBase
        this.dataType.DataModel.DateTime = // DateTime from stored vaule in DataBase

        return View(this.dataType);

Any work around for the above issue?

Advance Thanks, HV


Solution

  • It appears that you forgot to instantiate this.dataType.Datamodel:

    this.dataType.DataModel = new DataModel();
    this.dataType.DataModel.Activity = // Activity from stored vaule in DataBase
    this.dataType.DataModel.DateTime