0

I am learning C# MVC using dotnetfiddle web to write code. I have created a new project with the default code of dotnetfiddle for MVC type, but I want to display the question in the alert instead of the answer.

I want to know how to pass parameters to the controller from the view.

This is the ajax method:

$.ajax({
    url: '@Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
    data: JSON.stringify({Answer: '', Question: $('#Question').val()}),
    type: 'POST',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function(resp) {
        openAlert(resp.result);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) { 
            openAlert("ERROR: " + errorThrown); 
    }
});

And this is the controller method:

[HttpPost]
public JsonResult GetAnswer(string question)
{               
    int index = _rnd.Next(_db.Count);
    var answer = _db[index];
    return Json(new { result = question});
}

You can check and test the code here: dotnetfiddle (Edit: it will be a good answer if it works here)

Kaido
  • 15
  • 4
  • In order to send JSON you need `data: JSON.stringify({Answer: '', Question: $('#Question').val()}),` or jQuery will send `Answer=&Question=xyz` instead –  Aug 03 '21 at 09:27
  • I have already changed ```data: {Answer: '', Question: $('#Question').val()},``` to ```data: JSON.stringify({Answer: '', Question: $('#Question').val()}),``` but I get a null var in the controller. – Kaido Aug 03 '21 at 09:54
  • 1
    Possible duplicate: [How to pass json POST data to Web API method as an object?](https://stackoverflow.com/questions/20226169/how-to-pass-json-post-data-to-web-api-method-as-an-object) –  Aug 03 '21 at 10:13
  • Did not work for me. Maybe the error comes for another reason but I doubt it because is the example code autogenerated by dotnetfiddle. – Kaido Aug 03 '21 at 10:23

4 Answers4

0

This is the method I used to pass parameters to controller

First, assign the parameter you want to pass to a variable with the value from the input id as stated in your dotnetfiddle

var questionParam = $("#Question").val();

Then for passing it to AJAX, I think your method is already correct, this is how I do it

$.ajax({
    url: '/Home/GetAnswer?question=' + questionParam ,
    type: 'POST',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function(resp) {
        openAlert(resp.result);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) { 
            openAlert("ERROR: " + errorThrown); 
    }
});

This method works for me in my project, if the value is a string I think you don't need to stringify the value.

I'm still a beginner as well so maybe my method is wrong or not the best way to do it, I hope it helps you.

  • You're inserting the question (unescaped btw) as GET param, not as POST param. –  Aug 03 '21 at 10:10
  • If I do that I get a sintex error. I provide a source code to test it without installing anything. – Kaido Aug 03 '21 at 10:17
0

You are getting the value of the question in the action because your action has got a single parameter string question in there.

What you need to do is:

  1. Send a json object from the view
  2. In the action user a model with two properties (Answer and Question) to get the value sent by the view
  3. Then in the action you decide what data you need to send to view

View: Send JSON object to action:

JSON.stringify({Answer: '', Question: $('#Question').val()})

When you get the data returned from controller:

openAlert(resp.Answer);

Controller:

public JsonResult GetAnswer(MyQA model)
{
    // model.Answer
    // model.Question
    // Your business logic goes here

    return Json(new { result = model});
}

Here is the MyQA class:

public class MyQA
{
    public string Answer { get; set; }
    public string Question{ get; set; }
}
Rahatur
  • 3,147
  • 3
  • 33
  • 49
  • I already did the changes you propose but the alert still not working. Can you check it in your browser please: [dotnetfiddle](https://dotnetfiddle.net/UpivQ5) – Kaido Aug 03 '21 at 10:16
  • @Kaido can you point out where you are facing the problem? And what error you are getting? – Rahatur Aug 03 '21 at 12:20
0

dotnetfiddle had a problem with this line: contentType: "application/json; charset=utf-8",

change script to :

$('.submit').click(function() {
  if ($('form').valid()) {
    $.ajax({
      url: '@Url.Action("GetAnswer", "Home")',
      data: {
        Answer: '',
        Question: $('#Question').val()
      },
      type: 'POST',
      dataType: 'json',
      success: function(resp) {
        openAlert('Answer :' + resp.Answer + ' -----Question : ' + resp.Question);
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        openAlert("ERROR: " + textStatus);
      }
    });
  } else {
    closeAlert();
  }
});

change action GetAnswer to :

[HttpPost]
public JsonResult GetAnswer(string Answer,string Question)
{               
   int index = _rnd.Next(_db.Count);
     var answer = _db[index];
     return Json(new {Answer = answer,Question = Question});
}
Meysam Asadi
  • 6,438
  • 3
  • 7
  • 17
0

These code changes will work for you. If you wanna verify check the fiddle. DotNetFiddle

Client side Changes

                $.ajax({
                    url: '@Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
                    data: {"Answer": '', "Question": $('#Question').val()},
                        type: 'POST',
                        success: function(resp) {
                            openAlert(resp.Question);
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) { 
                            openAlert("ERROR: " + errorThrown); 
                        }
                    });

Server Side Changes

[HttpPost]
        public JsonResult GetAnswer(SampleViewModel model)
        {               
            int index = _rnd.Next(_db.Count);
            var answer = _db[index];
            return Json(model);
        }
Muhammad Asad
  • 1,772
  • 16
  • 23