Reputation: 313
I'm trying to pass the value of my inputs to a C# controller, but it always errors out when it tries to use the values because they are null.
$(document).ready(function () {
$(document).on('submit', '#form', function () {
var data = JSON.stringify({
'val1': $("#val1").val(),
'val2': $("#val2").val()
});
$.ajax({
type: "POST",
url: 'url',
contentType: "aplication/json",
data: data,
success: function () {
alert("It works")
},
error: function () {
alert("It failed");
}
});
return false;
});
});
Controller:
public IActionResult CheckForm(string val1, string val2)
{
//Do stuff
}
I appreciate any guidance on what step I am missing because as of now I have run out of ideas.
Upvotes: 1
Views: 47
Reputation: 2932
I tried to use your code, but encountered a lot of problems. The returned result is null like yours. I changed your code and finally got the value. The code result is as follows:
Controller:
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(string val1, string val2)
{
// Do stuff
}
View:
<form>
<input id="val1" />
<input id="val2" />
<input type="submit" value="test" id="form2"/>
</form>
@section scripts{
<script>
$("form").on("submit", function (event) {
var data = {
'val1': $("#val1").val(),
'val2': $("#val2").val()
};
console.log(data)
$.ajax({
type: "POST",
url: '/test/index',
//dataType: 'json',
//contentType: "application/json",
data:data,
success: function () {
alert("It works")
},
error: function (error) {
console.log(error)
alert("It failed");
}
});
return false;
});
</script>
}
Upvotes: 1
Reputation: 43969
Create view model
public ValViewModel
{
public string Val1 { get; set; }
public string Val2 { get; set; }
}
Action method:
public IActionResult CheckForm([FromBody] ValViewModel viewModel)
{
// Do stuff
}
Upvotes: 0