1

我正在尝试在我的简单测试应用程序中使用 ajax。我有一个下拉列表、一个按钮和一个 div,我在其中显示从下拉列表中选择的项目。这是代码:

我的控制器:

public ActionResult Index()
    {
        if (Session["items"] == null)
        {
            Session["items"] = new List<Item>();
        }

        var items = new Item[] { 
            new Item("1", "one"),
            new Item("2", "two"),
            new Item("3", "three")
        };

        ViewBag.list = Session["items"];
        ViewBag.items = new SelectList(items, "Id", "Value");
        return View(new Item());
    }

    [HttpPost]
    public ActionResult Index(Item item)
    {
        ((List<Item>)Session["items"]).Add(item);
        return RedirectToAction("Index");
    }

物品类别:

public class Item
{
    private string id;
    private string value;

    public Item(string id, string value)
    {
        this.id = id;
        this.value = value;
    }

    public Item()
    {
    }

    public string Id { get { return id; } set { id = value; } }
    public string Value { get { return value; } set { this.value = value; } }
}

我的观点:

@model TestExample.Models.Item
@{
   ViewBag.Title = "Index";
 }
@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "itemList" }))
{
  <div id="btn">
    @Html.DropDownListFor(m => m.Id, ViewBag.items as SelectList)
    <input type="submit" value="Add" />
  </div>
}

<div id="itemList">
  @foreach (TestExample.Models.Item item in ViewBag.list as     List<TestExample.Models.Item>)
  {
    <h1>@item.Value</h1>
  }
</div>

问题是,每当我从列表中选择项目并按添加时,我都会复制我的下拉框和按钮以及显示在 div 中的项目。这发生在第一次单击之后,并且在它之后我总是看到两个下拉框和按钮,并且列表中的项目是重复的。这是什么原因?我该如何解决它..

谢谢

4

1 回答 1

1

在 ajax 发布后,您将相同的页面插入:

<div id="itemList">
  ...
</div>

这就是为什么你有 2 个按钮等。在这个动作中:

[HttpPost]
public ActionResult Index(Item item) { ... }

您只需要返回包含列表项的部分视图。

于 2012-12-22T10:58:52.727 回答