2015-01-07 120 views
0

我有一個包含多個不同選項卡的表單。主選項卡包含有關此人的所有主要信息,其餘選項卡由多個列表組成。ajax插入後,加載所有插入列表,無需重新加載頁面

其中一個選項卡包含與該人相關的所有評論的列表。該選項卡還有一個允許用戶插入新評論的按鈕。

我所做的是做一個ajax調用並加載創建視圖,用視圖替換列表。像這樣的東西。

$("#btnNewAnnotation").click(function (e) { 
     $.ajax({ 
      url: "/Annotations/Create", 
      cache: false, 
      data: { personId: $("#personId").val(), withouLayout: true }, 
      type: "GET", 
      success: function (data, textStatus, jqXHR) { 
       alert("alert of success!!"); 
       $("#annotationContent").html(data); 
      }, 
      error: function (statusText, errorText) { 
       alert(errorText); 
      } 
     }); 
    }); 

現在它做什麼它傾倒的局部視圖,允許我把新的HTML的annotationContent

public ActionResult Create(string personId, string withouLayout) 
    { 
     ViewBag.AnnotationTypeId = new SelectList(db.annotationtypes, "AnnotationTypeId", "Name"); 
     annotations annotation = new annotations(); 
     annotation.PersonId = personid; 

     return PartialView(annotation); 
    } 

控制器這一切工作真的很好,沒有任何問題。我遇到的問題是在數據庫中插入註釋之後。我想要做的就是重裝再次與所有評論列表,但只更新DIV annotationContent

我有以下的AJAX

$("#createAnnotationForm").on("submit", function() { 
     e.preventDefault(); 
     $.ajax({ 
      url: "/Annotations/Create", 
      cache: false, 
      data: $(this).serialize(), 
      dataType: "json", 
      type: "POST", 
      success: function (data, textStatus) { 
       //This alert never gets Called!! 
       alert("ajax insert success"); 
      }, 
      error: function (statusText, errorText) { 
       alert('Error: ' + errorText) 
      } 
     }); 
    }); 

我這樣做的原因是因爲有多個形式該視圖和我只想提交此表單。我的控制器具有以下

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create(annotations annotations) 
{ 
    try 
    { 
     db.annotations.Add(annotations); 
     db.SaveChanges(); 
    } 
    catch(Exception ex) 
    { 
    } 

    return PartialView(db.annotations); 
} 

當我提交表單,我得到的錯誤

The model item passed into the dictionary is of type 'System.Data.Entity.DbSet`1[RecruitmentWeb.Models.annotations]', but this dictionary requires a model item of type 'RecruitmentWeb.Models.annotations'. 

我明白爲什麼我得到這個錯誤,但我不知道我該怎麼重裝我的評論列表而無需重新加載整個頁面。任何人有任何想法?

回答

0

您通常希望傳入註釋類的單個實例。

我假設註釋是一個DbSet,註釋是你的實際類。

因此,這將是

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create(annotation annotation) 
{ 
    try 
    { 
     db.annotations.Add(annotation); 
     db.SaveChanges(); 
    } 
    catch(Exception ex) 
    { 
    } 

    return PartialView(db.annotations); 
} 
相關問題