ASP.NET MVC表单值未在Post上设置

时间:2010-09-02 10:49:57

标签: asp.net asp.net-mvc-2

我有一个名为Problem的模型对象:

[Table(Name = "Problems")]
public class Problem
{
    [HiddenInput(DisplayValue = false)]
    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
    public int ProblemId { get; set; }

    [Display(ResourceType = typeof(Resources.Resources), Name = "TablePersonStudentName")]
    [Column] public int StudentId { get; set; }

    [Display(ResourceType = typeof(Resources.Resources), Name = "TableCommunicationTypesName")]
    [Column] public int CommunicationTypeId { get; set; }

    [Display(ResourceType = typeof(Resources.Resources), Name = "TableProblemTypeName")]
    [Column] public int ProblemTypeId { get; set; }

    [Display(ResourceType = typeof(Resources.Resources), Name = "TableMitigatingCircumstanceLevelName")]
    [Column] public int MitigatingCircumstanceLevelId { get; set; }

    [Display(ResourceType = typeof(Resources.Resources), Name = "TableProblemDate")]
    [Column] public DateTime? DateTime { get; set; }

    [Display(ResourceType = typeof(Resources.Resources), Name = "TableProblemOutline")]
    [Column] public string Outline { get; set; }

    [Display(ResourceType = typeof(Resources.Resources), Name = "TableProblemFile")]
    [Column] public byte[] MitigatingCircumstanceFile { get; set; }

    [Display(ResourceType = typeof(Resources.Resources), Name = "TableProblemAbsentFrom")]
    [Column] public DateTime? AbsentFrom { get; set; }

    [Display(ResourceType = typeof(Resources.Resources), Name = "TableProblemAbsentUntil")]
    [Column] public DateTime? AbsentUntil { get; set; }

    [Display(ResourceType = typeof(Resources.Resources), Name = "TableProblemRequestedFollowUp")]
    [Column] public DateTime? RequestedFollowUp { get; set; }

    public CommunicationType CommunicationType { get; set; }

    public MitigatingCircumstanceLevel MitigatingCircumstanceLevel { get; set; }

    public ProblemType ProblemCategory { get; set; }

    public ICollection<ProblemCommunication> ProblemCommunications { get; set; }

    public ICollection<AssessmentExtension> AssessmentExtensions { get; set; }

    public ICollection<User> Users { get; set; }

}

由于此模型包含来自其他数据库表的大量对象,因此我使用viewModel在视图中使用下拉列表:

public class ProblemViewModel
{
    public Problem Problem { get; set; }
    public SelectList Students { get; set; }
    public SelectList CommunicationType { get; set; }
    public SelectList MitigatingCircumstanceLevel { get; set; }
    public SelectList ProblemType { get; set; }
    public MultiSelectList ProblemUsers { get; set; }

    public ProblemViewModel(Problem problem, ISqlStudentRepository sqlStudentRepository, 
        ISqlCommunicationTypeRepository sqlCommunicationTypeRepository, ISqlMitigatingCircumstanceLevelRepository sqlMitigatingCircumstanceRepository,
        ISqlProblemTypeRepository sqlProblemTypeRepository, ISqlUserRepository sqlUserRepository,
        string username)
    {
        this.Problem = problem;
        this.Students = new SelectList(sqlStudentRepository.Students.ToList(), "StudentId", "FirstName");
        this.CommunicationType = new SelectList(sqlCommunicationTypeRepository.CommunicationTypes.ToList(), "CommunicationTypeId", "Name");
        this.MitigatingCircumstanceLevel = new SelectList(sqlMitigatingCircumstanceRepository.MitigatingCircumstanceLevels.ToList(), "MitigatingCircumstanceLevelId", "Name");
        this.ProblemType = new SelectList(sqlProblemTypeRepository.ProblemTypes.ToList(), "ProblemTypeId", "TypeName");
        this.ProblemUsers = new MultiSelectList(sqlUserRepository.Users.Where(s => s.UserName != username).ToList(), "UserId", "UserName");
    }
}

这是在导航到问题/创建控制器方法时生成的:

public ViewResult Create()
    {
        string username = User.Identity.Name;

        return View("Edit", new ProblemViewModel(new Problem(), sqlStudentRepository, 
            sqlCommunicationTypeRepository, sqlMitigatingCircumstanceRepository,
            sqlProblemTypeRepository, sqlUserRepository, username));
    }

这是ascx视图:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<BournemouthUniversity.WebUI.Models.ProblemViewModel>" %>
                 
        <div class="editor-field">
            <%: Html.HiddenFor(model => model.Problem.ProblemId)%>
            <%: Html.ValidationMessageFor(model => model.Problem.ProblemId)%>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Problem.StudentId) %>
        </div>
        <div class="editor-field">
            <%: Html.DropDownListFor(model => model.Problem.StudentId, Model.Students)%>
            <%: Html.ValidationMessageFor(model => model.Problem.StudentId)%>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Problem.CommunicationTypeId)%>
        </div>
        <div class="editor-field">
            <%: Html.DropDownListFor(model => model.Problem.CommunicationTypeId, Model.CommunicationType)%>
            <%: Html.ValidationMessageFor(model => model.Problem.CommunicationTypeId)%>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Problem.ProblemTypeId)%>
        </div>
        <div class="editor-field">
            <%: Html.DropDownListFor(model => model.Problem.ProblemTypeId, Model.ProblemType)%>
            <%: Html.ValidationMessageFor(model => model.Problem.ProblemTypeId)%>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Problem.MitigatingCircumstanceLevelId)%>
        </div>
        <div class="editor-field">
            <%: Html.DropDownListFor(model => model.Problem.MitigatingCircumstanceLevelId, Model.MitigatingCircumstanceLevel)%>
            <%: Html.ValidationMessageFor(model => model.Problem.MitigatingCircumstanceLevelId)%>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Problem.DateTime)%>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Problem.DateTime, new { @class = "datePicker" })%>
            <%: Html.ValidationMessageFor(model => model.Problem.DateTime)%>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Problem.Outline)%>
        </div>
        <div class="editor-field">
            <%: Html.TextAreaFor(model => model.Problem.Outline, 6, 70, new { maxlength = 255 })%>
            <%: Html.ValidationMessageFor(model => model.Problem.Outline)%>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Problem.AbsentFrom)%>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Problem.AbsentFrom, new { @class = "datePicker" })%>
            <%: Html.ValidationMessageFor(model => model.Problem.AbsentFrom)%>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Problem.AbsentUntil)%>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Problem.AbsentUntil, new { @class = "datePicker" })%>
            <%: Html.ValidationMessageFor(model => model.Problem.AbsentUntil)%>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Problem.RequestedFollowUp)%>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Problem.RequestedFollowUp, new { @class = "dateTimePicker" })%>
            <%: Html.ValidationMessageFor(model => model.Problem.RequestedFollowUp)%>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Problem.Users)%>
        </div>
        <div class="editor-field">
            <%: Html.ListBoxFor(model => model.Problem.Users, Model.ProblemUsers, new { @class = "multiselect" })%>
            <%: Html.ValidationMessageFor(model => model.Problem.Users)%>
        </div>

        <p>
            <input type="submit" class="button" value="Save" />
        </p>

<% } %>

然而,当我提交表单时,输入了[HttpPost]编辑控制器操作,但对于大多数值都为null ...

[HttpPost]
    public ActionResult Edit(Problem problemValues)
    {
        try
        {
            MembershipUser myObject = Membership.GetUser();
            String UserId = myObject.ProviderUserKey.ToString();

            Problem problem = problemValues.ProblemId == 0
                ? new Problem()
                : sqlProblemRepository.Problems(UserId).First(p => p.ProblemId == problemValues.ProblemId);
            TryUpdateModel(problem);

            if (ModelState.IsValid)
            {
                sqlProblemRepository.SaveProblem(problem);
                TempData["message"] = problem.ProblemId + " has been saved.";

                if (Request.IsAjaxRequest())
                {
                    return Json(problem);
                }

                return RedirectToAction("Details", "Student", new { problem.StudentId });
            }
            else
                return View(problem);
        }
        catch (Exception ex)
        {
            if (Request.IsAjaxRequest())
            {
                return Json(null);
            }
            else
            {
                TempData["message"] = "Record Not Found.";
                return RedirectToAction("Index");
            }
        }
    }

alt text

任何关于此的想法都会被理解,它似乎发生在我的大多数表格中,我有下拉列表然而我不明白为什么所有的值都是空的,即使是非下拉字段。

提前致谢...

乔纳森

3 个答案:

答案 0 :(得分:2)

我建议您将您的存储库与模型分开。这样,您传递给视图的就是模型。 View和ViewModel都不需要任何存储库。它的工作方式是控制器使用存储库来获取模型并将此模型传递给视图:

public ViewResult Create()
{
    string username = User.Identity.Name;
    Problem model = someRepository.FetchModel(username);
    ProblemViewModel viewModel = someMapper.ConvertToViewModel(model);

    return View("Edit", viewModel);
}

提交动作:

[HttpPost]
public ViewResult Create(ProblemViewModel viewModel)
{
    // viewModel will contain all the fields that you have corresponding
    // inputs in the View
    ...
}

答案 1 :(得分:1)

如果你检查生成的html,我想你会发现表单字段是使用点符号...基本上发回模型。问题而不仅仅是问题......其中有你的......呃....问题

修改的 我没有很好地解释这个我认为....你的html字段应该回发属性,这些属性将映射到动作接受的模型,在这种情况下,动作期待一个问题模型....但是你的html字段回发的是一个有问题的模型......而不是IS A Problem。

答案 2 :(得分:0)

我认为您需要将“修改”操作的签名更改为

[HttpPost]
public ActionResult Edit(int problemId, Problem problemValues)
{
.
.
}

似乎你遇到的问题与MVC Custom ViewModel and auto binding

相同