I've been fiddling with the default MVC fiddle on dotnetfiddle. The default picks a random answer to any question (or an non-null text entered). I am trying to get it to give a specific answer ("No one!") to any question that contains the word "Who".
[HttpPost]
public JsonResult GetAnswer(SampleViewModel qa)
{
Console.Write(qa);
int index = _rnd.Next(_db.Count);
if (qa.Question != null)
{
qa.Answer = qa.Question.Contains("Who") ? "No one!" : _db[index];
}
Console.WriteLine(qa);
return Json(qa);
}
The default GetAnswer method, which is called on POST, had a string parameter named question. I don't know why that should be, as the ajax call passes/ed an object with two string members (Answer and Question) to the method. I've changed it to accept an object SampleViewModel type, which has two string members.
$.ajax({
url: '@Url.RouteUrl( new { action="GetAnswer", controller="Home"})',
data: {Answer: "", Question: $('#Question').val()},
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resp) {
console.log(resp);
openAlert(resp.Answer);
}});
I haven't changed that object passed. I have, though, changed the JSON object sent back from method (to a SampleViewModel obj) and then, in the ajax success function, am sending just the Answer in the object to a js function that updates the text in a span. (I haven't changed any of the said js/jquery code other than in the ajax call).
The problem is that the controller method always seems to be getting a null object passed in. Console.Write() for some reason isn't working in this fiddle, but I've tried this project in VS Code with debugger and confirmed that.
How do I get the object correctly passed in to the method?
Edit: When I examine $('#Question').val() in the Chrome developer console, it does indeed always show the text entered in the question text-box.
Edit(2): The SampleViewModel definition:
namespace HelloWorldMvcApp
{
public class SampleViewModel
{
[Required]
[MinLength(10)]
[MaxLength(100)]
[Display(Name = "Ask Magic 8 Ball any question:")]
public string Question { get; set; }
//See here for list of answers
public string Answer { get; set; }
}
}
1 Answer 1
Remove the contentType
from your ajax call. If you make it application/json
, you'd have to stringify.
SampleViewModel
class?