MVC - 使用Ajax呈现局部视图
-
09-09-2019 - |
题
我有这样的标记在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 displayas一个新页 在浏览器和不更新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它确实是这样 不加载新页。???
马尔科姆
解决方案
当使用此:
<a href="javascript:document.forms[0].submit()">
...你应该知道,这是不一样的。
<input type="submit" />
这不会引发onsubmit事件,以及MVC的AJAX事件处理程序没有被调用。
要确认这是问题,添加
<input type="submit" />
的形式内,尝试。
最后,只是从你的链接调用的onsubmit()
<a href="#" onclick="document.forms[0].onsubmit()">
其他提示
可能是值得确保你已经正确地在你的页面(母版页)引用的ajaxmvc和jQuery脚本。如果这些是不正确的一个新的页面将被显示,而不是在目标DIV正确的输出。
的RenderPartial采取动作名称,用户控制的不名称,因此替换“IngredientsListControl”与“UpdateStep2”,你的操作名。
不隶属于 StackOverflow