Shakeer Hussain
Shakeer Hussain

Reputation: 2526

Model textBox field passing as null value to controller in MVC

Date TextBox Field passing as null value from View to Controller

Here is my Model class

public class VehcileMakeModel
    {
        //public VehicleModel VehicleModel { get; set; }
        //public List<VehicleMake> VehcileMakeList { get; set; }

        [Required(ErrorMessage = "...")]
        public string Model { get; set; }

        [Required(ErrorMessage = "...")]
        public DateTime? Year { get; set; } 

        [Required(ErrorMessage = "...")]
        [Display(Name = "Make")]
        public int SelectedMake { get; set; }

        public IEnumerable<SelectListItem> MakesList { get; set; }
    }

Strongly Typed View:

@model MvcApplication1.Models.VehcileMakeModel

@{
    ViewBag.Title = "CreateMakeModel";
}

<h2>CreateModel</h2>
@using (Html.BeginForm("SaveModel", "iRateBook"))
{
<table>
    <tr>
        <td>@Html.Label("Select Make")</td>
        <td>@Html.DropDownListFor(m => m.SelectedMake, Model.MakesList)</td>
    </tr>
    <tr>
        <td>Enter Model </td>
        <td>@Html.TextBoxFor(m => m.Model)</td>
    </tr>
    <tr>
        <td>Enter Model Year</td>
        <td>
            @Html.TextBoxFor(m=>m.Year)
        </td>
    </tr>
    <tr><td><input type="submit" value="Save" /> </td></tr>
</table>
}

When i click on Save button entered textbox values must pass to controller.

Controller Name

public ActionResult SaveModel(VehcileMakeModel VMM)
        {
            int ? makeid = VMM.SelectedMake;
            string strModel = VMM.Model.ToString();

            VehicleDataContext obj = new VehicleDataContext();
           // obj.VehicleModels.Add(VMM);

            obj.SaveChanges();


            return View("index");
        }

enter image description here

Why Yer field passing as Null value in Controller?

Upvotes: 0

Views: 1325

Answers (1)

Alex Art.
Alex Art.

Reputation: 8781

The issue is that you specified Year property as DateTime? and not as int/string. Default model binder expects dates to be sent in format defined by application culture. For example if you set in web.config

<globalization uiCulture="en-US" culture="en-US" />

Model binder will expect MM/dd/yyyy date format (excluding time part.

Since you need only a year, I would simply change Year property to be integer

public int? Year { get; set; }

If you really need a DateTime? property on the model (which I doubt), you can create it it based on Year property:

public class VehcileMakeModel
{
    [Required(ErrorMessage = "...")]
    public int? Year { get; set; } 

    public DateTime? YearDt
    {
         return this.Year.HasValue ? new DateTime(this.Year.Value,1,1) : null;
    }
}

Upvotes: 1

Related Questions