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를 실행하면 브라우저의 새 페이지를 표시하고 engredientListDiv를 업데이트하지 않습니다.
이것이 내 컨트롤러 동작입니다
[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 Eventhandler는 호출되지 않습니다.
이것이 문제인지 확인하려면 추가하십시오
<input type="submit" />
양식 안에서 시도해보십시오.
마지막으로 링크에서 onsubmit ()를 호출하십시오.
<a href="#" onclick="document.forms[0].onsubmit()">
다른 팁
페이지에서 AJAXMVC 및 JQUERY 스크립트를 올바르게 참조했는지 확인할 가치가 있습니다 (마스터 페이지). 이들이 잘못된 경우 대상 DIV의 올바른 출력 대신 새 페이지가 표시됩니다.
RenderPartial은 사용자 컨트롤의 이름이 아닌 작업 이름을 가져 오므로 "ingredientsListControl"을 조치 이름 인 "updatestep2"로 바꾸십시오.
제휴하지 않습니다 StackOverflow