将Ajax.BeginForm与MVC 4一起使用 - 异步添加到我的模型集合中是不行的

时间:2014-01-18 17:20:48

标签: asp.net-mvc-4 asynchronous model

我正在尝试创建一个小型足球网站,用户可以在其中创建一个新团队,然后在另一个div中异步显示用户创建的所有团队。所以基本上创建一个团队然后添加到团队列表中。所有这些都在模型中。

现在,我想以异步方式执行此操作,因为它很好用,但它在我的代码中不起作用。我要么缺少某些东西,要么我不能做什么。

控制器

public ActionResult TeamManagement()
        {
            modelTeamSelect modelTeamSelect = new modelTeamSelect();
            return View(modelTeamSelect);
        }

        [HttpPost]
        public ActionResult TeamManagement(string btnSubmit, modelTeamSelect modelTeamSelect)
        {
            switch (btnSubmit)
            {
                case "Add Team":
                    // For now - add to collection but not use DAL
                    modelTeamSelect.teams.Add(modelTeamSelect.team);
                    //modelTeamSelect.team.TeamName = string.Empty;
                    break;
            }
            return View(modelTeamSelect);
        }

查看

@model Website.Models.modelTeamSelect

@{
    ViewBag.Title = "Football App";
}
@section featured {

}

@using (Ajax.BeginForm(new AjaxOptions
{
    HttpMethod = "POST",

    Url = "Home/TeamManagement",

    OnComplete = "teamAdded()"
}))
{

        <div id="divTeams" style="float:left">
        <h3>Create a new team:</h3>

                @Html.LabelFor(m => m.team.TeamName)
                 @Html.TextBoxFor(m => m.team.TeamName)
                 <input type="submit" value="Add Team" name="btnSubmit" />

        </div>

        <div id="divCreatedTeams" style="float:left">
         <h3>Your created teams:</h3>
        @if (Model.teams.Count > 0)
        {
            for (int i = 0; i < Model.teams.Count; i++)
            {
                @Html.TextBoxFor(m => m.teams[i].TeamName)
            }
        }
        </div>

        <div id="divLeagues">

        </div>

}

模型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Website.Models
{
    public class modelTeamSelect
    {
        public modelTeamSelect()
        {
            teams = new List<modelTeam>();
            team = new modelTeam();
        }

        public List<modelTeam> teams { get; set; }
        public modelTeam team { get; set; }
    }
}

我在项目中使用了正确的javascript引用,因为我最近解决了这个问题。

enter image description here

enter image description here

为什么我的UI不会改变以反映列表的新内容?

1 个答案:

答案 0 :(得分:0)

我不明白将提交按钮字符串传递给Action。但是为了将ViewModel传递给Action,我认为你必须编写自己的模型绑定器。如果你想要,你可以尝试在动作中单独获取模型并将它们组合在Action

 public ActionResult TeamManagement(List<modelTeam> teams, modelTeam team)

并将它们组合在viewModel中的动作中。

只是一个消化如果你想用ajax检索它们异步我做的是返回局部视图(我觉得你的情况更好)或者json