2013-12-09 3 views
1

텍스트 상자의 검색 조건을 기반으로 테이블에 데이터를 표시하려고합니다. Ajax를 사용하지 않고 구현했지만 jquery를 사용하여 컨트롤러 메소드를 호출하고 테이블 데이터를 업데이트하는 방법을 모른다. 내 문제를 해결하려고 노력하십시오. 감사합니다 ...ASP.net에서 ajax를 사용하여 테이블의 데이터 검색 MVC

Index.cshtml

@model IEnumerable<MvcApplication4.Models.tbl_product> 
@{ 
    Layout = null; 
} 

    <!DOCTYPE html> 
<html> 
<head> 
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script> 
    <title>Index</title> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      $('#Button1').click(function() { 
       alert("button clicked"); 
       $.ajax({ 
        type: 'POST', 
        contentType: "application/json; charset=utf-8", 
        url: 'Home/Index', 
        data: "{'searchString':'" + document.getElementById('searchString').value + "'}", 
        async: false, 
        Success: function (response) { 
         alert("Success"); 

          window.location.reload(); 
        }, 
        error: function() { alert("error"); } 
       }); 

      }); 
     }); 
    </script> 
</head> 
<body> 
    @* @using (@Html.BeginForm("Index", "Home")) 
    {*@ 
    @Html.TextBox("searchString"); 
    <input type="button" value="filter" id="Button1" /> 
    @* }*@ 
    <table id="showData"> 
     @{Html.RenderPartial("SearchList");} 
    </table> 
</body> 
</html> 

SearchList.cshtml (부분보기)

@foreach (var item in Model) 
{ 
<tr> 
<td>@item.ProductName</td> 
<td>@item.ProductId</td> 
<td>@item.ProductDesc</td> 
</tr> 
} 

HomeController.cs

public class HomeController : Controller 
    { 
     // 
     // GET: /Home/ 
     ProductEntities dbentity = new ProductEntities(); 
     public ActionResult Index() 
     { 
      return View(dbentity.tbl_product.ToList()); 
     } 

     [HttpPost] 
     public ActionResult Index(string searchString) 
     { 
      var query = dbentity.tbl_product.Where(c => c.ProductName.Contains(searchString)); 
      return View(query.ToList()); 
     } 

    } 

답변

0

당신의 아약스 요청과 같아야합니다

 $.ajax({ 
     url: '/<ControllerName>/<MethodName>', 
     type: "POST", 
     data: requestData, 
     contentType: "application/json;charset=utf-8", 
     success: function (data, textStatus, XMLHTTPRequest) { 

      //Success callback handling 
     }, 
     error: function (XMLHTTPRequest, textStatus, errorThrown) { 
      //Error callback handling 
     }, 
     cache: false //whether you want to cache the response or not. 
    }); 
+0

위의 코드를 변경하고 ajax를 구현했지만 작동하지 않으며 테이블이 업데이트되지 않습니다. – user2802591

1
$.ajax({ 
      url: '/ControllerName/ActionName', 
      type: "POST", 
      data: {criteria: 'criteria'}, 
      contentType: "application/json", 
      success: function (data) { 
      //Replace existing table with the new view (with the table). 
      } 
     }); 

// 키 컨트롤러없이 ControllerName을 작성하십시오.

+0

변경했지만 아약스 부분이 실행되지 않습니다, 위의 코드를 편집했습니다 ... – user2802591

0

나는 정확한 대답을하지는 않으나 그것을 얻을 수 있도록 도와 줄 것입니다.

두 단계가 있습니다

먼저는 요청이 수행되고 있는지 확인 받아야하고, 응답이 브라우저에 도착되고 있습니다.

그렇게하려면
  • 은 당신의 방법에 그것을 할 수 있습니다 만 alert("Success");을 떠나이 실행 되 고 확인.
  • 그보다 나은 브라우저의 개발자 콘솔 (Chrome을 선호하지만 IE 또는 FireFox + FireBug 애드온을 사용할 수도 있음)은 F12를 사용합니다. 중단 점을 설정하고 변수 값과 코드 흐름을 검사하십시오. th을 참조하십시오.
  • 는 서버 작업에 중단 점을 설정하고 전나무 부분이 잘 작동하는지있어 일단은

둘째을 실행 수표 사용하여 succes에는 수신 데이터와 테이블 내용을 대체하는 기능 응답. jQuery를 사용하면 여러 가지 방법으로이 작업을 수행 할 수 있습니다. 예 :

이 코드를 실행하고 브라우저의 개발자 콘솔에서 응답 내용을 검사 할 수 있습니다. 이것은 javascript를 사용하기 시작할 때 일들을 단순화시킵니다.

(액션이 전체 테이블을 생성 한 경우 내용 대신 대상을 대체하는 jQuery의 replaceWith을 사용할 수 있습니다.이 경우에는 사용하지 마십시오).

최종 알림 :이 코드를 제거하십시오. window.location.reload(); !!! 이렇게하면 전체 페이지가 현재 URL로 다시로드되므로 미리 수행 한 작업이 모두 손실됩니다.

1
   $.ajax({ 
        type: 'POST', 
        contentType: "application/json; charset=utf-8", 
        url: 'Home/Index', 
        data: JSON.stringify({'searchString':document.getElementById('searchString').value }), 
        async: false, 
        Success: function (response) { 
         alert("Success"); 
         //append the data in between table tbody like, 
         $('table tbody').html(response); 
         //No window.location.reload(); It will cause page reload initial data will appear in grid. 
        }, 
        error: function() { alert("error"); } 
       }); 
       return false 

희망이 있습니다.

+0

+1 for $ ('table tbody') .html (response); –

관련 문제