2009-04-15 122 views
11

我有這個標記在MVC應用程序。MVC - 使用Ajax呈現局部視圖

<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所以它 不會加載新的一頁。???

馬爾科姆

+0

調用的onsubmit()我們一直使用完整,應用程序相對路徑的部分名稱,例如Html.RenderPartial(「〜/查看/主頁/ ModuleNewUser.ascx」) – 2009-04-18 06:16:43

+0

是否顯示部分作爲一個新的頁面?或者其他一些頁面?你的部分內容是什麼? – 2009-04-18 12:39:19

回答

8

當您使用此:

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

...你應該知道,這是不一樣的

<input type="submit" /> 

它不會提高onsubmit事件,以及MVC的AJAX事件處理程序是不叫。

要確認這是問題,添加

<input type="submit" /> 

表單內,並嘗試一下。

最後,只是從你的鏈接

<a href="#" onclick="document.forms[0].onsubmit()"> 
-2

的RenderPartial採取動作的名稱,而不是用戶控件的名稱,所以用「UpdateStep2」,你的動作名稱取代「IngredientsListControl」。

+1

對不起,但我很確定它沒有。這就是RenderAction所包含的MvcFutures的功能。 – 2009-06-02 19:36:04

2

可能是值得確保你已經正確引用的ajaxmvc和jQuery腳本在你的頁面(母版頁)。如果這些不正確,將會顯示新頁面而不是目標div中的正確輸出。

+0

正是我想說的。找不到其他理由。 :) – 2009-06-02 19:31:17