복붙노트

[JQUERY] 어떻게 양식을하지 않고 ASP.NET MVC 컨트롤러에 문자열의 배열을 게시 할 수 있습니까?

JQUERY

어떻게 양식을하지 않고 ASP.NET MVC 컨트롤러에 문자열의 배열을 게시 할 수 있습니까?

해결법


  1. 1.나는 내가 한 테스트 응용 프로그램에 대한 코드를 포함하는 내 대답을 수정했습니다.

    나는 내가 한 테스트 응용 프로그램에 대한 코드를 포함하는 내 대답을 수정했습니다.

    업데이트 :이 (@DustinDavis '대답 당) 다시 작동 할 수 있도록 true로'전통 '설정을 설정하기 위해 jQuery를 업데이트했습니다.

    먼저 자바 스크립트 :

    function test()
    {
        var stringArray = new Array();
        stringArray[0] = "item1";
        stringArray[1] = "item2";
        stringArray[2] = "item3";
        var postData = { values: stringArray };
    
        $.ajax({
            type: "POST",
            url: "/Home/SaveList",
            data: postData,
            success: function(data){
                alert(data.Result);
            },
            dataType: "json",
            traditional: true
        });
    }
    

    그리고 여기 내 컨트롤러 클래스의 코드는 다음과 같습니다

    public JsonResult SaveList(List<String> values)
    {
        return Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
    }
    

    난 그 자바 스크립트 함수를 호출 할 때, 내가 말하는 경고를 얻을 "목록에서 첫 번째 항목을 '항목 1'". 도움이 되었기를 바랍니다!


  2. 2.참고 : JQuery와는 게시물 데이터를 직렬화하는 방법을 변경했습니다.

    참고 : JQuery와는 게시물 데이터를 직렬화하는 방법을 변경했습니다.

    http://forum.jquery.com/topic/nested-param-serialization

    당신은 사실, 다른 현명한에 '전통'설정을 설정해야

    { Values : ["1", "2", "3"] }
    

    로 나올 것입니다

    Values[]=1&Values[]=2&Values[]=3
    

    대신에

    Values=1&Values=2&Values=3
    

  3. 3.답변 주셔서 감사합니다 여러분. 또 다른 빠른 해결책은 문자열로 JSON 개체를 변환 할 true로 설정 전통적인 매개 변수 jQuery.param 방법을 사용하는 것입니다 :

    답변 주셔서 감사합니다 여러분. 또 다른 빠른 해결책은 문자열로 JSON 개체를 변환 할 true로 설정 전통적인 매개 변수 jQuery.param 방법을 사용하는 것입니다 :

    $.post("/your/url", $.param(yourJsonObject,true));
    

  4. 4.배열로 데이터를 게시하지 마십시오. 목록에 바인딩, 키 / 값 쌍은 각각의 키에 대해 동일한 값으로 제출해야한다.

    배열로 데이터를 게시하지 마십시오. 목록에 바인딩, 키 / 값 쌍은 각각의 키에 대해 동일한 값으로 제출해야한다.

    이 작업을 수행하는 양식을 필요가 없습니다. 당신은 당신이 $ .post 호출에 포함 할 수있는 키 / 값 쌍의 목록이 필요합니다.


  5. 5..NET4.5, MVC (5)에서

    .NET4.5, MVC (5)에서

    자바 스크립트 :

    JS에서 개체 :

    게시 않습니다 메커니즘.

        $('.button-green-large').click(function() {
            $.ajax({
                url: 'Quote',
                type: "POST",
                dataType: "json",
                data: JSON.stringify(document.selectedProduct),
                contentType: 'application/json; charset=utf-8',
            });
        });
    

    씨#

    사물:

    public class WillsQuoteViewModel
    {
        public string Product { get; set; }
    
        public List<ClaimedFee> ClaimedFees { get; set; }
    }
    
    public partial class ClaimedFee //Generated by EF6
    {
        public long Id { get; set; }
        public long JourneyId { get; set; }
        public string Title { get; set; }
        public decimal Net { get; set; }
        public decimal Vat { get; set; }
        public string Type { get; set; }
    
        public virtual Journey Journey { get; set; }
    }
    

    제어 장치:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Quote(WillsQuoteViewModel data)
    {
    ....
    }
    

    개체 접수 :

    이것은 당신에게 시간을 절약 할 수 있기를 바랍니다.


  6. 6.또한 객체가 아닌 문자열의 목록과 함께 노력하고 또 다른 구현 :

    또한 객체가 아닌 문자열의 목록과 함께 노력하고 또 다른 구현 :

    JS :

    var postData = {};
    postData[values] = selectedValues ;
    
    $.ajax({
        url: "/Home/SaveList",
        type: "POST",
        data: JSON.stringify(postData),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(data){
            alert(data.Result);
        }
    });
    

    그 'selectedValues'를 가정하면 객체의 배열입니다.

    제어기의 매개 변수는 대응 ViewModels의리스트이다.

    public JsonResult SaveList(List<ViewModel> values)
    {    
        return Json(new { 
              Result = String.Format("Fist item in list: '{0}'", values[0].Name) 
        });
    }
    

  7. 7.내가 여기 설명하고있는 바와 같이,

    내가 여기 설명하고있는 바와 같이,

    당신은 당신이 솔루션을 사용할 수 있습니다 MVC 액션에 사용자 정의 JSON 개체를 전달하려면, 그것이 마치 마법처럼 작동합니다.

    public string GetData() {
      // InputStream contains the JSON object you've sent
      String jsonString = new StreamReader(this.Request.InputStream).ReadToEnd();
    
      // Deserialize it to a dictionary
      var dic =
        Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < String,
        dynamic >> (jsonString);
    
      string result = "";
    
      result += dic["firstname"] + dic["lastname"];
    
      // You can even cast your object to their original type because of 'dynamic' keyword
      result += ", Age: " + (int) dic["age"];
    
      if ((bool) dic["married"])
        result += ", Married";
    
      return result;
    }
    

    이 솔루션의 이점이 있습니다, 당신은 쉽게 원래 유형의 개체를 캐스팅 할 수 인수의 각 조합과 그 옆에 새로운 클래스를 정의 할 필요가 없다는 것입니다.

    당신은 당신의 작업을 용이하게하기 위해 다음과 같이 헬퍼 방법을 사용할 수 있습니다 :

    public static Dictionary < string, dynamic > GetDic(HttpRequestBase request) {
      String jsonString = new StreamReader(request.InputStream).ReadToEnd();
      return Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < string, dynamic >> (jsonString);
    }
    

  8. 8.당신은 사용하여 설치 글로벌 매개 변수를 수

    당신은 사용하여 설치 글로벌 매개 변수를 수

    jQuery.ajaxSettings.traditional = true;
    

  9. 9.대답은 그 주셔서 감사합니다, 그래서 내 상황에서 나에게 많은 도움이되었습니다. 그러나 미래에 대한 참조 사람들은 모델하고 검증하기 위해 결합해야한다. 필 Haack에서이 포스팅은 MVC 2 http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx이 설명

    대답은 그 주셔서 감사합니다, 그래서 내 상황에서 나에게 많은 도움이되었습니다. 그러나 미래에 대한 참조 사람들은 모델하고 검증하기 위해 결합해야한다. 필 Haack에서이 포스팅은 MVC 2 http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx이 설명

    이 사람을 도움이되기를 바랍니다.

  10. from https://stackoverflow.com/questions/309115/how-can-i-post-an-array-of-string-to-asp-net-mvc-controller-without-a-form by cc-by-sa and MIT license