【问题标题】:How to pass data to ajax function with json?如何使用json将数据传递给ajax函数?
【发布时间】:2019-11-04 05:29:28
【问题描述】:

我需要从 URL 中获取 id,从文本框中获取注释值,将其保存到数据库并使用 ajax 显示在页面上。 我不确定我的控制器和 ajax 函数中的语法应该如何正确。

控制器

 [HttpPost]
    public JsonResult AddComment(int id, string comment)
    {
        if (ModelState.IsValid)
        {
            return Json(true); // what should be here 
        }
        return Json(true);
    }

阿贾克斯

    $('#submit').click(function () {
        $.ajax({
            url: '/Form/AddComment',
            method: 'POST',
            data: {
                id: 4,               //how to get id from url?
                comment: 'test'      //how to get textbox value?
            },
            success: function (data) {
                console.log(data)
            },
            error: function (a, b, c) {
                console.log('err')
            }
        })
    });

这只是告诉我它有效,但我不知道如何前进

【问题讨论】:

  • 您的代码到底有什么问题?如何在客户端检索您放入请求的数据?如何阅读动作中的参数?
  • 是的,没错。我不知道该怎么做
  • 在这种情况下,您的问题太宽泛了。我建议分解任务并单独研究它们。即how to read from the URL querystringhow to get the value from a textbox。关于在 C# 中保存到数据库,我们需要知道您使用的是什么 DBMS,以及您如何与它通信,但同样只需研究这些关键字,您就会找到答案。
  • 您能展示 url 和输入字段的示例以供评论吗?
  • @Dodsonnn 你搞定了吗?

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


【解决方案1】:

根据您的要求,您必须在客户端进行适当的表单处理,才能获得idcomment 等变量。您可以使用强类型模型绑定来获取表单值并在提交时处理它们,或者您可以使用 JavaScript 技术来处理表单变量。要从 URL 中提取 id,您可以使用 Regular Expression 或其他 JavaScript 字符串解析技术。我给你一个简单的例子,使用 JavaScript 从 URL 获取 id 和从文本框中获取 comment

您的输入控件如下所示:

<input type="text" id="commentBox" name="Comment" class="form-control" />

为了使用 AJAX 将表单变量 POST 到控制器来实现您想要的功能,请参考以下代码 sn-p:

AJAX:

<script type="text/javascript">

var url = 'http://www.example.com/4'; //Example URL string
var yourid = url.substring(url.lastIndexOf('/') + 1);
var yourcomment= document.getElementById('commentBox').value;

var json = {
            id: yourid, //4
            comment: yourcomment 
           };

$('#submit').click(function (){
    $.ajax({
        url: '@Url.Action("AddComment", "Form")',
        type: "POST",
        dataType: "json",
        data: { "json": JSON.stringify(json)},
        success: function (data) {
         console.log(data)
         },
         error: function (data) {
         console.log('err')
         },
    });
};
</script>

您可以像这样在 Controller 中获取您的值:

using System.Web.Script.Serialization;

[HttpPost]
public JsonResult AddComment(string json)
{
    if (ModelState.IsValid)
    {
        var serializer = new JavaScriptSerializer();
        dynamic jsondata = serializer.Deserialize(json, typeof(object));

        //Get your variables here from AJAX call
        string id= jsondata["id"];
        string comment=jsondata["comment"];

        // Do something here with your variables. 
    }
    return Json(true);
}

【讨论】:

  • 正如@Rahul Sharma 所说,您也可以从 id 的强类型模型属性中获取 id(如果存在),而无需从 url 中读取,例如:var id = @Model.id。这个 jQuery 必须在页面中,而不是在外部文件中。
【解决方案2】:

我的解决方案如下所示:

控制器:

       [HttpPost]
    public JsonResult AddComment(int id_usr,string comment)
    {
        if (ModelState.IsValid)
        {
            Comments kom = new Comments();
            kom.DateComment = DateTime.Now;
            kom.Id_usr = id_usr;
            kom.Comment = comment;
            db.Comments.Add(kom);
            db.SaveChanges();
            return Json(kom);
        }
        return Json(null);

    }

查看

var url = window.location.pathname;
var idurl = url.substring(url.lastIndexOf('/') + 1);
$('#submit').click(function () {
        console.log('click')
        $.ajax({
            url: '/form/AddComment',
            method: 'POST',
            data: {
                comment: $("#Comments_Comment").val(),
                id_usr: idurl,
            },
            success: function (data) {
                console.log(data),

谢谢大家指导我解决问题

【讨论】:

    猜你喜欢
    • 2018-09-27
    • 1970-01-01
    • 2011-06-19
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    相关资源
    最近更新 更多