I'm trying to pass some data from my view that has been input by the user, so that I can dynamically change a label based on the results the controller method returns.
I can access the label ID in my form and change it through the javascript function, but I can't seem to access and pass the form values through to my Controller method.
My method is properly called on the submission of the form, and after some logic on the form parameters passed by my script, should return a string message ready for my script to display on the page.
My script:
@section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#submit1").click(function () {
$.ajax({
type: 'POST',
url: '/Home/GetResult',
data: { number: $("#param1").val(), string: $("#param2").html(), string: $("#param3").html() },
success: function (result) {
alert(result);
},
error: function () {
$("#rates").html("Something went wrong");
}
});
});
})
</script>
}
My HTML:
<form class="form-inline" name="NumberInput" method="post">
<input type="number" class="form-control mb-2 mr-sm-2" name="param1" id="param1" placeholder="Insert number">
<div class="input-group mb-2 mr-sm-2">
<select class="custom-select mr-sm-2" name="param2" id="param2">
<option selected>Choose...</option>
</select>
</div>
<div class="input-group mb-2 mr-sm-2">
<select class="custom-select mr-sm-2" name="param3" id="param3">
<option selected>Choose...</option>
</select>
</div>
<button type="button" onclick="GetResult()" class="btn btn-primary mb-2" id="submit1" name="submit1" value="Get Result">Result</button>
<div class="form-check mb-2 mr-sm-2">
<label class="form-check-label" name="rates" id="rates">Currency 1 = Currency 2</label>
</div>
My Controller method:
[HttpPost]
public ActionResult GetResult(double param1, string param2, string param3)
{
var result = "";
// some logic with param1, 2 and 3
return Ok(result);
}
At this point I'd like to just use my result to update my #rates message .html as I am doing in my script's error section. But all 3 parameters passed through to GetResult() are 0, null and null, so I always end up returning an error.
I think I'm not accessing the IDs and passing them properly, but I've also been reading many other answers and some mention json.stringify(). But I'm accessing my #rates ID just fine, so I'm not sure why the 3 parameters from the form's input aren't being passed to my method. Any suggestions are appreciated.