gpt4 book ai didi

ajax - MVC - 使用 Ajax 呈现局部 View

转载 作者:行者123 更新时间:2023-12-04 02:16:22 24 4
gpt4 key购买 nike

我在 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>

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

这是我的 Controller 操作
[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()">

关于ajax - MVC - 使用 Ajax 呈现局部 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/750543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com