2016-08-02 7 views
0

私はSearchStudent()アクションで作業しています。コードに問題があります。欠けているものがあります。 Partial Viewを返し、私はSearchフォームで最初Index page内部Partial View Pageを表示したいと一度フォームがPost requestを使用して、それを提出いっぱい。私はそれがアヤックスから私たちのURLをハードコーディングする悪い習慣です知っているので、私は<p>内の私のかみそりビューからdata-属性を使用してい ..私はすべてのことがIndex view内で起こるようにしたいので、すべてが使用してAJAXをしたいです要素は@Url.Action()を使用して、URLそこに置きます。問題は、@Url.Actionを使用すると、SearchStudent() Actionの代わりにインデックスアクションにルーティングされ、partial viewの代わりに同じIndex pageが2回表示され、URLがajaxにハードコードされているときに、何が起こっているのかがわかりますか?razorとAjaxの@ Url.Action()を個別に使用して呼び出します。

たぶん、あなたは私のコードを見て、より良い理解します:

アクションメソッド(私は最初の部分図を表示したい)

public PartialViewResult SearchStudent() 
     {    
      return PartialView(); 
     } 
     [HttpPost] 
     [ValidateAntiForgeryToken] 
     public JsonResult SearchStudent(string name) 
     { 
      List<Student> list = db.Students.Where(s => s.Name == name).ToList(); 
      return Json(list, JsonRequestBehavior.AllowGet); 
     } 

Indexビュー(部分図を示すように関わるだけのセクション) :

<div> 
    <p class="hand" id="pSearch" data-urlSearch="@Url.Action("SearchStudent","Students")"> Search by name</p> 
    <div id="ShowFormSearch"></div> 
</div> 

jQueryの機能(私はアヤックスurl: "Students/SearchStudent"内に直接置く場合、それは動作しますが、それは良い習慣ではありません):

function ShowSearchPage() 

{ 
    $.ajax({ 
     type: 'get', 
     url: $("#pSearch").data('urlSearch'),   
    }).success(function (result) { 
     $("#ShowFormSearch").html(result) 
    }).error(function() { 
     $("#ShowFormSearch").html("An error occurred") 
    }) 
} 

答えて

2

あなたの問題は$("#pSearch").data('urlSearch')ではStudents/SearchStudentを返していません。その理由は、HTML 5つのデータattrbutesのために、それは、小文字する必要があります。

また
$("#pSearch").data('urlsearch') 

$("#pSearch").data('urlSearch') 

を交換し、私はデータattrbuteを設定するため、常に小文字を使用することをお勧めします。

data-urlsearch="@Url.Action("SearchStudent", "Home")" 
+0

それが動作するようになりました! html5 thxsでそれについて知らなかった – AlexGH

1

あなたはこのようなあなたのjavascript関数を変更してみてください、私たちは結果が何であるかを知っているようでした:

function ShowSearchPage() { 

    var url = $("#pSearch").data('urlSearch'); 
    alert(url); 

    $.ajax({ 
     type: 'get', 
     url: url, 
    }).success(function (result) { 
     $("#ShowFormSearch").html(result) 
    }).error(function() { 
     $("#ShowFormSearch").html("An error occurred") 
    }) 
} 
+0

アラートが 'に変更しcase.Justデータ属性が常に下に入力する必要があるためですundefined'メッセージ – AlexGH

+1

示し - VARのurl = $( "#のpSearchを")のデータ( 'urlsearch')。それが動作するようになりまし –

+0

感謝!! – AlexGH

関連する問題