复杂类型

时间:2015-08-14 05:06:49

标签: asp.net asp.net-mvc-4 razor mvc-editor-templates

我是stackoverflow的沉默读者,几乎在所有情况下,我都会从本网站的其他人的帖子中找到我的问题的解决方案,直到昨天我遇到困难但无法找到解决方案。

以下是我的应用架构的一些解释:

我在一个单独的c#项目中有代码优先实体模型,我将它引用到我的web项目中。我有以下实体:

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; }
}

在视图方面,我有一个带有Index.cshtml的Home视图,它指的是Views/Shared/EditorTemplates/University.cshtml

 @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})

这是University.cshtml的外观:

@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)})

在Index.cshtml上,当我点击“提交”按钮时,它会将Employee对象发回服务器,但

Employee.University.TotalDegrees为null,即使用户填写了值

如果我从University.cshtml中删除@Html.HiddenFor(model=>model.UniversityId),则Employee.University在帖子中显示为空。

我尝试使用@Html.EditorFor(model=>model.TotalDegrees)@Html.TextBoxFor(model=>model.TotalDegrees),但似乎没有一个可以使用

如果我将所有内容从University.cshtml移动到主视图,那么一切似乎都能正常工作。

任何帮助或建议都表示赞赏。

2 个答案:

答案 0 :(得分:0)

你的问题是你写了错误的lambda x => Model.TotalDegrees。只需解决此问题:

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

答案 1 :(得分:0)

废话!花了16个小时来确定设计师给了我这个

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

除了我自己的表单之外,还有一个与EditorTemplate中每个字段相关联的表单,并且它将表单发布到no :(

感谢Stephen的帮助,并为浪费时间而感到抱歉:)

相关问题