0

我使用JQuery Ajax在Asp.Net MVC Partial View中提交表單帖子。在JQuery Ajax提交後,部分視圖渲染不正確

部分視圖位於引導選項卡中的其中一個選項卡內(有4個選項卡,每個選項卡具有其部分視圖)。還有一個視圖,它涵蓋了所有這些選項卡。並且有一個覆蓋全部的佈局。

蓋子查看裏面這是局部視圖操作方法調用:

@Html.Action("AddProductPartial", "Products") 

局部視圖操作:

[HttpPost] 
     public ActionResult AddProductPartial(ProductCategoryBrand pcb) 

     { 
      if (ModelState.IsValid) 
      { 
       Product p = new Product(); 
       p.CategoryID = Convert.ToInt32(pcb.CategoryViewModel.Kategori); 
       p.BrandID = Convert.ToInt32(pcb.BrandViewModel.BrandName); 
       p.ExchangeName = pcb.ExchangeViewModel.ExchangeName; 

       ProductRepository prep = new ProductRepository(); 
       prep.AddProduct(p) 
      } 
      loadBrands(); 
      getRates(); 

      return View(pcb); 

     } 

JQuery的阿賈克斯:

$('#saveProduct').click(function() { 

    $.ajax({ 
     url: "/Products/AddProductPartial", 
     type: 'POST',   
     data: "{'CategoryID':" + categoryID + ", 'BrandID':" + brandID + ",'ExchangeName':" + exchangeName + "}", 
     async:true,    
     contentType: "application/json; charset=utf-8", 
     dataType: "json",   
     success: function (data) { 
      alert("success"); 
     }, 
     error: function (xhr, status, error) { 
      alert(xhr.responseText) 

     } 
    }); 
}); 

下面填充這些語句從dropdownlisfor D b。我添加了這些方法,因爲在Ajax提交後,部分視圖中的dropdownlist爲空異常。

loadBrands(); 
getRates(); 

添加這些語句後,問題發生。

提交後,部分視圖渲染怪異:Bootstrap導航標籤不再可見。因爲覆蓋部分視圖的視圖根本不呈現。當我改變這一行:

return View(pcb); 

return Partial View(pcb); 

然後只呈現自身局部視圖,獨立於所有的佈局。

請你幫忙。謝謝。

+0

我可以看Ajax代碼?也許在ajax函數的成功回調中,您將替換整個網頁,而不僅僅是包含部分的HTML元素。 –

+0

我添加了JQuery Ajax代碼。 @ChristopherMMiller我縮短了參數,因爲這裏的代碼似乎太長了 – Zeynep

+0

您應該用@ Html.Partial(「AddProductPartial」)和您的公共ActionResult AddProductPartial替換@ Html.Action(「AddProductPartial」,「Products」)' '應該返回一個帶有有用信息的Json對象,如成功/錯誤/新產品ID等 – JamieD77

回答

1

這裏是局部視圖的最簡單的例子:

public class HomeController : Controller 
{ 
    [HttpPost] 
    public PartialViewResult GetXlFile() 
    { 
     return PartialView("_ExcelGrid"); 
    } 

    public ActionResult GetXlFile(int? id) 
    { 
     return View(); 
    } 

_ExcelGrid.cshtml在共享:

A Partial View Info 

檢視:

<!DOCTYPE html> 
@*credit to 
    https://stackoverflow.com/questions/5410055/using-ajax-beginform-with-asp-net-mvc-3-razor*@ 
<html> 
<head> 
    <meta name="viewport" content="width=device-width" /> 
    <title>Index800</title> 
    <script src="~/Scripts/jquery-1.12.4.min.js"></script> 
    <script type="text/javascript"> 
     $(function() { 
      $('#pvButton').click(function (event) { 
       $.ajax({ 
        url: this.action, 
        type: "POST", 
        data: $(this).serialize(), 
        success: function (result) { 
         $('#result').html(result); 
        } 
       }); 
       return false; 
      }); 
     }); 
    </script> 
</head> 
<body> 
    <form> 
     <div> 
      <input id="pvButton" type="button" value="OK" /> 
      <div id="result"></div> 
     </div> 
    </form> 
</body> 
</html>