MVC - 使用Ajax渲染局部视图

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会在浏览器中显示为一个新页面,而不更新ingredientlistdiv。
这是我的控制器动作。
[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 中的方法,以便它不会加载新页面。???

Malcolm


我们一直使用完整的、相对于应用程序的路径来引用部分视图名称,例如 Html.RenderPartial("~/Views/Home/ModuleNewUser.ascx")。 - Jarrod Dixon
它是将部分内容显示为新页面吗?还是其他页面?你的部分内容是什么? - James Avery
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()">

1
然而,我强烈建议您使用标准的提交按钮(<input type="submit" />,Html.SubmitButton MVC助手)。如果您使用<a href...>/JS提交表单,将会遇到很多麻烦 - 在所有浏览器中使其正常工作非常困难。您可以使用CSS样式更改提交按钮的外观,并且在所有情况下都能正常工作。 - Alex42

2

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


正是我想说的。仅凭外表看不出其他原因。 :) - Arnis Lapsa

-2

RenderPartial接受一个操作名称,而不是用户控件的名称,因此请将“IngredientsListControl”替换为您的操作名称“UpdateStep2”。


1
抱歉,但我很确定它不会。这是RenderAction所做的事情,它包含在MvcFutures中。 - Arnis Lapsa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接