2017-11-29 3 views
0

드롭 다운 선택 드롭 다운 값을 선택하면 컨트롤러 동작 방법이 표시되지 않습니다. 선택된 값이 아약스에 바인딩하지만 컨트롤러 액션 메소드에 바인딩되지 see our page컨트롤러 데이터 전달보기

<div class="row"> 
    <div class="col-lg-3"> 
    <fieldset class="form-group"> 
     <label class="form-label semibold control-label">Generic</label> 
     @Html.DropDownList("MasterGenericID", null, "--- Select Generic ---", new { @class = "select2-arrow" }) 
    </fieldset> 
    </div> 
$('#btnsearch').click(function() { 
    var genericID = $('#MasterGenericID').val(); 
    $.ajax({ 
    type: 'POST', 
    url: "@Url.Action("ProductMasterController", "ProductMasterview")", 
    data: JSON.stringify(GenericID), 
    contentType: "application/json", 
    dataType: 'json', 
    success: function(data) { 
     // if (response.id > 0) 
     alert("test" + data.GenericID); 
    }, 
    async: true // make it true if you want to make an async call. 
    }); 
}); 
public ActionResult ProductMasterview(string GenericID) 
    if (Convert.ToInt32(GenericID) > 0) 
    { 
    return View(dPMSP.GetAllProductsUsingGenericID(GenericID)); 
    } 
    else 
    { 
    Generic_Bind(); 
    Therapeutic_Bind(); 
    SubTherapeutic_Bind(); 
    Formulation_Bind(); 
    return View(dPMSP.GetAllProducts()); 
    } 
} 

Error page

감사

+0

작업 정의에'{' –

답변

0

것처럼 C# 코드가 보일 것 같은.

이 라인

data: JSON.stringify(GenericID), 

당신은 변수 GenericID를 사용하고 살펴보고 있지만, 그것은 어디 정의되어 있지 않습니다. 자바 스크립트는 대소 문자를 구분합니다을 기억하십시오. 올바른 대소 문자를 사용하고 있는지 확인하십시오.

지금이 라인

url: '@Url.Action("ProductMasterController", "ProductMasterview")', 

당신은 잘못 Url.Action 도우미 방법을 사용하는 좀 봐. 2 개의 매개 변수를 사용하는 오버로드를 사용하는 경우 첫 번째 매개 변수는 동작 이름이어야하고 두 번째 매개 변수는 컨트롤러 이름이어야합니다. 또한 접미어 Controller이 필요 없습니다. 그래서

url: "@Url.Action("ProductMasterview", "ProductMaster")", 

내가, 당신은 json와 같은 Ajax 호출의 데이터 유형 속성을 지정하는 눈치 또 다른 문제 같은 것을해야한다. $.ajax 메서드는이 속성 값을 사용하여 서버에서 오는 데이터를 구문 분석합니다. 여기에 $.ajax에게 서버에서 JSON 응답을 기다리고 있다고 알려줍니다. 그러나 액션 메소드는 JSON이 아닌 HTML/Plain 텍스트 인 뷰 결과를 반환합니다. 따라서 코드가 예상대로 작동하지 않습니다.

POST 호출을하고 있지만 작업 메서드가 HttpPost 특성으로 장식되어 있지 않은 것으로 나타났습니다. 따라서 아약스 호출은 액션 메소드에 영향을 미치지 않습니다. 또한 귀하의 질문에 어떤 유형의 데이터를 반환 할 것인지 명확하지 않습니다. (JSON/결과보기 -HTML).

보기 결과 (HTML 마크 업)를 반환하는 경우 부분보기 결과를 반환해야만 DOM의 일부를 업데이트 할 수 있습니다. 전체보기를 반환하는 경우 Ajax 호출을 할 필요가 없습니다 (동작 메서드 코드에서 else 부분의 4 메서드 호출을 볼 때 그렇게하려고한다는 느낌이 들게됩니다).

또한 올바른 데이터 형식을 사용하십시오.숫자 값을 전달하는 경우 을 param으로 사용하고 나중에 변환하는 대신 숫자 형식 (int 또는 long)을 사용하십시오. Convert.ToInt32은 전달한 값을 안전하게 int로 변환 할 수없는 경우 예외를 throw 할 수 있습니다 (예 : 12abc).

int을 매개 변수 유형으로 사용하십시오.

public ActionResult ProductMasterview(int genericId) 
{ 
    // some other logic you want to do . 
    return PartialView(dPMSP.GetAllProductsUsingGenericID(genericId)); 
} 

GetAllProductsUsingGenericID 메서드를 업데이트하여 문자열이 아닌 int 유형을 가져야합니다.

이제 클라이언트 측에서 data 속성에 선택한 옵션 값을 전달할 수 있습니다. 액션 메소드가 HttpPost 속성으로 장식되어 있지 않으므로 GET (기본 유형은 $.ajax)을 사용하면됩니다. 또한 액션 메소드 매개 변수 이름과 일치하는 키를 가진 js 객체에서 선택된 옵션 값을 보냅니다.

$('#btnsearch').click(function() { 
    var id = $('#MasterGenericID').val(); 
    $.ajax({ 
     url: "@Url.Action("ProductMasterview", "ProductMaster")", 
     data: { genericId: id } 
    }).done(function(response) { 
     console.log('Received response from server'); 
     console.log(response); 
     // If you want to update the DOM with the response 
     // Ex : $("#SomeDomElementId").html(response); 
    }).fail(function(x, a, e) { 
     alert(e); 
    }); 
}); 

조치 방법에서 JSON을 반환하려면 괜찮습니다. dataType 속성을 반드시 지정할 필요는 없으므로 jQuery는 응답 헤더를 기반으로 지능적으로 추측하려고 시도합니다.

+0

고맙습니다. 그 working #shyju –

+0

genericID가 controller 액션 메소드에 들어 왔지만, 동시에 두 개의 operation을 수행한다. 하나는 condition이고, 다른 하나는 else condition이고 다른 하나는 else else 만 표시한다. –

0

당신은 직접 대신 통과해야 아약스 호출에 값을 전달하는 GenericID 속성이있는 객체

(210)

예 -

$('#btnsearch').click(function() { 
    var value = $('#MasterGenericID').val(); 

    var data = { 
     GenericID: value 
    }; 

    $.ajax({ 
     type: 'POST', 
     url: "@Url.Action("ProductMasterview", "ProductMaster")", 
     data: JSON.stringify(data), 
     contentType: "application/json", 
     dataType: 'json', 
     success: function(data) { 
      // if (response.id > 0) 
      alert("test" + data.GenericID); 
     }, 
     async: true // make it true if you want to make an async call. 
    }); 
}); 
+0

이 없습니다.'data : data'를 사용하고'contentType' 옵션 만 삭제하면됩니다.'JSON.stringify() '를 사용할 필요가 없습니다. 그러나이 메소드는 html을 반환하기 때문에 예외가 발생합니다. json ='dataType' 옵션을 삭제하거나'dataType : 'html''을 지정하면 (그리고'async'는 기본적으로'true'입니다) –

+0

감사합니다. surya 유효한 응답 –

0

는 JS는해야

$('#btnsearch').click(function() { 
    var genericID = $('#MasterGenericID').val(); 
    var postData={ 
       GenericID:genericID 
       }; 
    $.ajax({ 
    type: 'POST', 
    url: '@Url.Action("ProductMasterController", "ProductMasterview")', 
    data: postData, 
    dataType: 'json', 
    success: function(data) { 
     // if (response.id > 0) 
     alert("test" + data.GenericID); 
    }, 
error: function(xhr, ajaxOptions, thrownError) { 
            alert('Failed to delete'); 
           } 
    }); 
}); 

그리고 귀하의 코드는 문제의 무리가 있습니다

[HttpPost] 
public ActionResult ProductMasterview(string GenericID) 
{ 
    if (Convert.ToInt32(GenericID) > 0) 
    { 

    //return View(dPMSP.GetAllProductsUsingGenericID(GenericID)); 
    //you can return only the genericId as you expect it at ajax success 
    return Json(new { GenericID = yourGenericId}); 
    } 
    else 
    { 
    Generic_Bind(); 
    Therapeutic_Bind(); 
    SubTherapeutic_Bind(); 
    Formulation_Bind(); 
    //return View(dPMSP.GetAllProducts()); 
    //you can return only the genericId as you expect it at ajax success 

    return Json(new { GenericID = yourGenericId}); 
    } 
} 
관련 문제