3

在以 http 发布表单提交时,我的模型丢失了一个值,我遇到了问题。

控制器方法:

[HttpGet]
public ActionResult AddTeam(int id)
{
    return PartialView("_AddTeam", ViewModelGenerator.TeamFormModel(id));
}

[HttpPost]
public ActionResult AddTeam(TeamFormModel model)
{
    TournamentTeamService.CreateTeam(model);

    return RedirectToAction("Index", "Tournament", null);
}

表格模型:

public class TeamFormModel
{
    public TeamViewModel Team { get; set; }
    public TournamentViewModel Tournament { get; set; }
    public List<PlayerViewModel> Players { get; set; }
}

该函数从控制器调用,它创建表单模型的新实例并从数据库中获取锦标赛并将其放入视图模型中

public static TeamFormModel TeamFormModel(int id)
{
    var _db = new DbContext();
    var model = new TeamFormModel();
    var tempModel = new TournamentViewModel();

    var temp = (from t in _db.tournament
                        where t.Id == id
                        select t).SingleOrDefault();

    tempModel.Id = temp.Id;
    tempModel.Name = temp.Name;
    tempModel.SignupStartDate = temp.SignupStartDate;
    tempModel.SignupEndDate = temp.SignupEndDate;
    tempModel.StartDate = temp.StartDate;
    tempModel.EndDate = temp.EndDate;
    tempModel.Description = temp.description;
    tempModel.TournamentType = temp.TournamentType;

    model.Players = new List<PlayerViewModel>();
    model.Tournament = tempModel;

    return model;
}

这是视图,缺少播放器列表输入的代码,这是因为它通过 jquery 附加到播放器表单 div 并且它运行良好,所以我认为它在这种情况下不相关。

@model Context.ViewModels.TeamFormModel

<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

@using (Html.BeginForm("AddTeam", "Tournament", FormMethod.Post, new { enctype = "multipart/form-data", @class = "form-horizontal" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <h2>Registering a team to @Model.Tournament.Name </h2>
    <div class="control-group">
        @Html.LabelFor(model => model.Team.Name)
        <div class="control">
            @Html.EditorFor(model => model.Team.Name)
        </div>
        <a  class="add-player-form" href="javascript:void(0)">Add a player</a>
        <div id="player-forms">

        </div>
    </div>    
    <div class="control-group">
        <div class="control" style="clear: both;">
            <input type="submit" value="Register" />
        </div>
    </div>
}

在我提交此表单之前,TeamFormModel 已完美设置,所有值都已插入,我只需将所有内容保存到 DB。但是,当它返回到控制器时,TeamFormModel 中的锦标赛变量为空。因此,当我将其发送到将其更改为 Db 模型并将其提交给 db 的函数时,每次都会失败。

我知道有一些方法可以解决这个问题,比如只保留锦标赛的 id 而不是整个模型,然后在提交表单后从 db 获取它,但它的行为方式确实让我感到烦恼。

我在stackoverflow上找不到关于这个特定问题的任何内容,有一些类似的问题,但没有任何东西以同样的方式呈现出来。

4

1 回答 1

3

你必须设置这样的东西

@Html.HiddenFor(x => x.TournmentID);

某些东西必须保留在渲染视图时传递到视图中的模型的值,这将在发布时将值传递回控制器

于 2013-05-15T02:22:05.093 回答