如何通过Jquery.ajax()将视图中的字符串值传递给ASP.NET MVC控制器

时间:2016-08-20 16:39:39

标签: c# jquery asp.net ajax asp.net-mvc

我的观点中有一个功能,如下所示:

function doIncriment() {
            var v1 = @ViewBag.CountNumber + 1;
            var v2 = @int.Parse(Request.QueryString["idForAnswer"]);
            var v3 = @int.Parse(Request.QueryString["View"]);
            var v5 = @int.Parse(Request.QueryString["answerNumber"]);
            var v6 = @Request.QueryString["title"];
            jQuery.ajax({
                url: '@Url.Action("pp", "Questions")',
                method: "POST",
                cache: false,
                data: { votingUp : v1, questionId : v2 , viewNumber : v3, numberOfAnswer : v5 , titleString : v6 }
            }).done(function (d) {
                jQuery("#lblResult").text(d);
            });
        }

我的控制器代码如下:

[HttpPost]
public string pp(string votingUp, int questionId, int viewNumber, int numberOfAnswer, string titleString, [Bind(Include = "ID,Vote,Answer1,View,Title,Question,Date")] Questions questions)
            {
                questions.ID = questionId;
                questions.Vote = int.Parse(votingUp);
                questions.View = viewNumber;
                questions.Date = DateTime.Parse("2016-08-10 23:39:33.000");
                questions.Answer1 = numberOfAnswer;
                questions.Title = titleString.ToString();
                questions.Question = "test test";
                db.Entry(questions).State = EntityState.Modified;
                db.SaveChanges();
                return (votingUp.ToString());
            }

int值工作正常。但每当我尝试传递任何字符串或日期时间数据时,ajax调用都没有响应。如何将这些值从我的ajax函数传递给控制器​​。

1 个答案:

答案 0 :(得分:0)

如果要发送字符串值,请确保您的方法参数也是string类型。目前,int参数为titleString

[HttpPost]
public string pp(string votingUp, int questionId, int viewNumber, int numberOfAnswer, 
   string titleString, [Bind(Include = "ID,Vote,Answer1,View,Title,
                                                      Question,Date")] Questions questions)
{
   // to do : Return something
}

我还建议您确保使用正确的数据类型。如果要发送数值(例如:votingUp),则不需要先使用字符串并将其转换回来。您可以直接使用int类型作为参数类型,并避免以后再进行转换

[HttpPost]
public string pp(int votingUp, int questionId, int viewNumber, int numberOfAnswer, 
   string titleString,
       [Bind(Include = "ID,Vote,Answer1,View,Title,Question,Date")] Questions questions)
{
  // to do : Return something
}

编辑:作为评论中提到的mmushtaq,您应该将@Request.QueryString["title"]的值包装在引号中,以便将其作为字符串值存储在变量v6中< / p>

var v6 = '@Request.QueryString["title"]';