Karl
Karl

Reputation: 39

Null value on POST in ASP.NET MVC

I'm learning ASP.NET MVC and I have the following problem.

The view "SelectProdotti" is

@model Models.SelectProdottiModel

@{
    ViewBag.Title = "Select Prodotti";
}

<h2>@ViewBag.Title</h2>

@using (Html.BeginForm("ProdottiToListino", "Listino", FormMethod.Post))
{ 


    @Html.HiddenFor(m => m.id)
    @Html.DisplayFor(m=> m.id)


    <input type="submit" value="Salva" />
}

The action that load the view

public ActionResult SelectProdotti(int id)
        {


            SelectProdottiModel model = new SelectProdottiModel();
            model.id = id;         

            return View(model);
        }

The model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Models
{
    public class SelectProdottiModel
    {


        public int id;

        public SelectProdottiModel()
        {                
        }
    }
}

The post action in the controller

[HttpPost]
        public ActionResult ProdottiToListino(SelectProdottiModel model)
        {

            return RedirectToAction("SelectProdotti", "Listino", new {id = model.id });
        }

I have written this code only to learn, it is useless. The problem is that model.id is always 0, i.e. the view don't post the value, where is the error ?

Upvotes: 1

Views: 2589

Answers (1)

Shyju
Shyju

Reputation: 218882

Currently Id is a field of your class with no GETTER/SETTER properties /methods.

Fields are typically used to store data internally inside a class ( and those will be with default-private visibility). Usually the value for the fields will be set/read via another public property or a method. With C# properties, this is much easier, If you want to allow a field to be readable and writable, you may create a public property like

public int Age {set;get;}

When you post the data from the form, The DefaultModelBinder(a class which maps the form data to a class object) will try to create an object of SelectProddottiModel class and try to set the values of the public properties which matches with name of the form items in the posted form data. If you do not make your field to a public property with set accessor,the model binder can not set the value.

Change your field Id to a property with set and get so that ModelBinder can set the value from the posted form data.

public class SelectProdottiModel
{
    public int id {set;get;}       
}

Also, C# typically uses PascalCasing. So I suggest you change your id property to Id

Upvotes: 2

Related Questions