Search code examples
asp.netasp.net-mvc-4razormvc-editor-templates

ASP MVC EditorTemplates for ComplexType


I am a silent reader of stackoverflow and in almost all cases I find solution to my problems from others' posts from this website until yesterday when I got stuck on something and can't find a solution.

Here is a little explanation on my app architecture:

I have code-first entity model in a separate c# project and I am referencing it to my web project. I have following entities:

public class Employee
{
    public Employee();
    public int EmployeeId {get;set;}
    public DateTime? DegreeCompleted{ get; set; }
    public virtual University University { get; set; }
}
public class University 
{
    public University();
    public int UniversityId {get;set;}
    public short? TotalDegrees{ get; set; }
    public short? TempTotalDegrees{ get; set; }
}

On view side, I have a Home view with Index.cshtml which is referring Views/Shared/EditorTemplates/University.cshtml as this:

 @using (Ajax.BeginForm("SaveEmployee", new AjaxOptions
 { 
            HttpMethod="POST",
            OnBegin="disableSubmit",
            OnComplete = "enableSubmit",
            OnFailure = "enableSubmit",
            InsertionMode=InsertionMode.Replace
            }))
      {
      @Html.HiddenFor(model=>model.EmployeeId)
      @Html.EditorFor(m => m.University, new { EmployeeId = Model.EmployeeId})

here is how University.cshtml looks:

@Html.HiddenFor(model=>model.UniversityId)
@Html.TextBoxFor(x => Model.TotalDegrees, new { @class="form-control", @min="5",@max="100",@type="number",@value=(Model.TotalDegrees.HasValue ? Model.TotalDegrees.Value : 5)})

on Index.cshtml, when I click on submit button it posts back the Employee object to server but

Employee.University.TotalDegrees is null, even though user fills in the value

If I remove @Html.HiddenFor(model=>model.UniversityId) from University.cshtml, Employee.University comes as null on post.

I have tried to use @Html.EditorFor(model=>model.TotalDegrees) and @Html.TextBoxFor(model=>model.TotalDegrees) but none of them seems to work

If I moved everyfrom from University.cshtml to main View, everything seems to work fine.

Any help or suggestion appreciated.


Solution

  • Crap !!! spent 16 hours to identify that designer gave me this

                   <form role='form'>
                    <div class="form-group">
                     <input />
                    </div>
                   </form>
    

    so apart from my own form, there was a form associated to each field in EditorTemplate and it was posting form to no where :(

    Thanks Stephen for your help and sorry for wasting time :)