11

我在 MVC 应用程序中有这个标记。

<div id="ingredientlistdiv">
    <% Recipe recipe = (Recipe)Model; %>
    <% Html.RenderPartial("IngredientsListControl", recipe.Ingredients); %>
</div>

<div id="ingrediententrydiv" align="left">
    <% using (Ajax.BeginForm("Add Ingredient", "Recipes/UpdateStep2", new AjaxOptions { UpdateTargetId = "ingredientlistdiv" }))
       { %>
    <p>
        <label for="Units">Units:</label><br />
        <%= Html.TextBox("Units", 0)%>
        <%= Html.ValidationMessage("Units", "*")%>
    </p>
    <p>
        <label for="Measure">Measure:</label><br />
        <%= Html.TextBox("Measure")%>
        <%= Html.ValidationMessage("Measure", "*")%>
    </p>
    <p>
        <label for="IngredientName">Ingredient Name:</label><br />
        <%= Html.TextBox("IngredientName")%>
        <%= Html.ValidationMessage("IngredientName", "*")%>
    </p>
    <p><a href="javascript:document.forms[0].submit()">Save Ingredient</a></p>
    <%= Html.Hidden("RecipeID", recipe.RecipeID.ToString())%>
    <% } %>
</div>

当它运行时,IngredientsListControl.ascx 在浏览器中显示为一个新页面,并且不更新成分列表div。

这是我的控制器动作

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UpdateStep2(FormCollection form)
        {
            var factory = SessionFactoryCreator.Create();

            using (var session = factory.OpenSession())
            {
                Recipe recipe = GetRecipe(session, Convert.ToInt32(form["RecipeID"]));

                Ingredient ingredient = new Ingredient();

                ingredient.UpdateFromForm(form);
                ingredient.Validate(ViewData);

                if (ViewData.ModelState.Count == 0)
                {
                    recipe.Ingredients.Add(ingredient);
                    session.Save(recipe);
                    return PartialView("IngredientsListControl", recipe.Ingredients);
                }


                return Content("Error");
            }
        }

我在这条线上做对了吗?

return PartialView("IngredientsListControl", recipe.Ingredients);

这就是我将控件呈现到 div 中的方式,因此它不会加载新页面。???

马尔科姆

4

3 回答 3

8

当你使用这个:

<a href="javascript:document.forms[0].submit()">

...您应该知道它与

<input type="submit" />

它不会引发 onsubmit 事件,并且不会调用 MVC 的 AJAX 事件处理程序。

要确认这是问题,请添加

<input type="submit" /> 

在表格内并尝试一下。

最后,只需从您的链接中调用 onsubmit()

<a href="#" onclick="document.forms[0].onsubmit()">
于 2009-07-12T11:12:24.537 回答
2

可能值得确保您在页面(母版页)中正确引用了 ajaxmvc 和 jquery 脚本。如果这些不正确,将显示一个新页面,而不是目标 div 中的正确输出。

于 2009-05-13T12:55:44.700 回答
-2

RenderPartial 采用动作名称,而不是用户控件的名称,因此将“IngredientsListControl”替换为“UpdateStep2”,即您的动作名称。

于 2009-04-18T06:11:27.970 回答