2

I am trying out with very basic MVC project using MVC 3.0 and Razor. Referring the turorial at this link.

I have created a strongly typed view for editing the Contacts using my model class called "Contact".

namespace Practice.Models
{
    public class Contact
    {
        public string firstName;
        public string lastName;
        public string mobileNumber;
    }
}

The "Index" method displays all the contacts using a list type view. When I click on "Edit" link against a contact, it displays the contact details in textboxes using an Edit View.

However, when I submit the Edit form, I am not getting the model values in controller action method. It shows null for each property. What exactly I may be missing here in such simple example?

DirectoryController

[HttpPost]
public ViewResult Edit(Contact model)
{
    contactRepository.Update(model);
    return View("Details", model);
}

View

@model Practice.Models.Contact
@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript">            </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"         type="text/javascript"></script>

@using (Html.BeginForm("Edit","Directory"))
{
@Html.ValidationSummary(true)
<fieldset>
    <legend>Contact</legend>
    @Html.TextBoxFor(m => m.firstName)
    @Html.TextBoxFor(m => m.lastName)
    @Html.TextBoxFor(m => m.mobileNumber)
    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Debug point

Anil Soman
  • 2,443
  • 7
  • 40
  • 64

1 Answers1

4

You are missing { get; set; } on your model properties

Ctrl_Alt_Defeat
  • 3,933
  • 12
  • 66
  • 116
  • Thanks KOL.. That solved the issue! But how come it could bind the values earlier without { get; set;} into textboxes? – Anil Soman May 09 '13 at 09:28
  • 1
    i believe if you declare a property without get; set; it would be read only - hence you may have seen the value in the textbox on your view - read more here - http://msdn.microsoft.com/en-us/library/w86s7x04.aspx – Ctrl_Alt_Defeat May 09 '13 at 09:48
  • Thanks KOL for the link but could find the clear answer to my question there. – Anil Soman May 09 '13 at 10:23
  • Found one useful thread [here](http://stackoverflow.com/questions/15976031/difference-between-properties-with-get-set-and-without-get-set) – Anil Soman May 09 '13 at 11:07