Pass Model from View to Controller

10,471

Solution 1

You should add hidden inputs containing your values :

@Html.HiddenFor(model => model.Id)
@Html.HiddenFor(model => model.Content)

This is because the model binder will search for inputs (like textboxes, or hidden fields) to get values and associated them with your model properties (based on input names). No input is created with DisplayFor, so the model binder can't find your values when you submit your form.

Solution 2

I think that @Html.DisplayFor values are not submitted.

Try including a @Html.HiddenFor for the same values.

Share:
10,471

Related videos on Youtube

user2323308
Author by

user2323308

Updated on September 15, 2022

Comments

  • user2323308
    user2323308 about 1 year

    I want to pass model to Post method of controller. When method is called it shows null value for content and 0 for Id. Ideally it should contain the values of model it has displayed.

    enter image description here

    View:

    @model MvcApplication4.Models.WorldModel
    @{
        ViewBag.Title = "Information";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    @using (Html.BeginForm("Information", "World", FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        <br />
        @Html.DisplayFor(model => model.Id)
        <br />
        @Html.DisplayFor(model => model.Content)
        <br />
        <input type="submit" value="Next" />
    }
    

    Controller: Method called when click on submit button.

            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Information(WorldModel worldModel)
            {
                CandidateSession cs = (CandidateSession)Session["Can"];
                var can = cs.Candidates.Where(x => x.IsNameDispalyed == false);
                if (can.Count() > 0)
                {
                    var can1 = can.First();
                    can1.IsNameDispalyed = true;
                    Session["Can"] = cs;
                    return View(new WorldModel() { Id = can1.Id, Content = can1.Name });
                }
                return View(new WorldModel());
            }
    

    Model:

    public class WorldModel
        {
            public int Id { get; set; }
    
            public string Content { get; set; }
        }