0

I need to get an id from the URL , comment value from textbox, save it to database and show on page with ajax. Im not sure how should look correct syntax in my controller and ajax function.

Controller

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

Ajax

    $('#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')
            }
        })
    });

this just show me that it work but i dont know how to move forward

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Dodsonnn
  • 65
  • 1
  • 11
  • What exactly is the issue with your code? How to retrieve the data you place in to the request on the client side? How to read the arguments in the action? – Rory McCrossan Jun 21 '19 at 11:11
  • yes, thats correct. i dont know how to do this – Dodsonnn Jun 21 '19 at 11:13
  • In that case your question is far too broad. I'd suggest breaking the tasks down and researching them individually. Ie, [how to read from the URL querystring](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript), [how to get the value from a textbox](https://stackoverflow.com/questions/463506/how-do-i-get-the-value-of-a-textbox-using-jquery). With regard to saving to a database in C# we'd need to know what DBMS you're using, and how you communicate with it, but again just research for those keywords and you'll find your answer. – Rory McCrossan Jun 21 '19 at 11:17
  • can you show sample of the url and input field for comment? – Bosco Jun 21 '19 at 11:43
  • @Dodsonnn Did you get this working? – Rahul Sharma Jun 24 '19 at 08:58
  • @RahulSharma Yes, i have finished this few minutes ago – Dodsonnn Jun 24 '19 at 10:28

2 Answers2

2

Based upon your requirement, you would have to do the appropriate form handling at client side in order to get your variables like id and comment. You can use strongly typed model binding to get your form values and process them on submit or you can use JavaScript techniques to process your form variables. To extract out id from a URL, you can use a Regular Expression or other JavaScript string parsing techniques. I am giving you a simple example of getting your id from a URL and comment from a text box using JavaScript:

Your input control would look like:

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

In order to achieve your desired functionality using AJAX to POST your form variables to controller, refer to the following code snippet:

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>

And you can get your values in your Controller like this:

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
  • 7,768
  • 2
  • 28
  • 54
  • As @Rahul Sharma said, you can get the id from the strongly typed model property of id as well, if it exists, without having to read from the url like: `var id = @Model.id`. This jQuery must be in the page and not in external file. – Jaggan_j Jun 21 '19 at 12:25
0

My solution looks like this:

controller:

       [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);

    }

View

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),

thank you all for guiding me to the solution

Dodsonnn
  • 65
  • 1
  • 11