簡體   English   中英

在C#中使用Ajax(url)傳遞多個參數

[英]passing multiple parameters using Ajax(url) in c#

在MVC中使用Ajax獲取多個參數時遇到麻煩。 我有兩個字段需要輸入。 用戶名和CommentText的輸入字段。

我在ajax的url部分中定義這些參數。 當我僅傳遞一個參數時,它工作正常(當分別嘗試時,兩個參數均適用),但是一旦我嘗試了后一個參數,則該參數不起作用。

Ajax功能:

$(function () {
    $("#button").click(function () {
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf8",
            url: "Home/AddComment?CommentText=" + $("#CommentText").val() + "&Username=" + $("Username").val(),
            dataType: "json",
            success: function (Comment) {
                //some function
            },
            error: function (xhr, err) {
                //some code
            }
        });
    });
});

有任何想法嗎? 我是否應該通過“數據”傳遞參數?

編輯: * 這是應該捕獲這些參數的控制器。 *

 public JsonResult AddComment(string commentText, string username)
        {
            Comment c = new Comment() { CommentText = commentText, Username = username };
            CommentRepository.Instance.AddComment(c);
            return Json(GetComments(), JsonRequestBehavior.AllowGet);

        }

您可以使用如下形式:

阿賈克斯

$.ajax({
    type: 'GET',
    url: 'Home/AddComment',
    data: { CommentText: $("#CommentText").val(), 
             Username: $("#Username").val() },
    cache: false,
    success: function (result) {            
        desc = result;
    }
});

然后在您的控制器中

public string AddComment(string CommentText, string Username)
{
    //your code here
}

希望這會幫助你。

 $(function () {
     $("#button").click(function () {
         $.ajax({
             type: "GET",
             contentType: "application/json; charset=utf8",
             url: "Home/AddComment",
              data: '{"CommentText":"' + $("#CommentText").val() + '", "Username":"' + $("Username").val() + '"}'
            dataType: "json",
             success: function (Comment) {
                 //some function
             },
            error: function (xhr, err) {
                 //some code
           }
        });
   });
});

您可以將所有變量/參數移動到一個數組中,然后可以嘗試以下操作..然后可以在C#中讀取這些數組值。

var val1=$("#componentName1").val();
var val2=$("#componentName2").val();
...
var parameterArray={val1,val2,val3....}
$.ajax({
         type: "GET",
         contentType: "application/json; charset=utf8",
         url: "Home/AddComment",
          data: parameterArray,
        dataType: "json",
         success: function (Comment) {
             //some function
         },
        error: function (xhr, err) {
             //some code
       }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM