I am new to Razor Pages. When a user selects a field from the dropdown menu, I want to return that value to a c# variable. My understanding is that this should be done via ajax call, but I cannot get the ajax call to work.
I'm getting confused as to what the ajax url field should be.
Also confused as to whether method="POST" typeof="submit" asp-page-handler="SelectedCalculation"
is necessary or in the right place.
Index.cshtml:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div class="dropdown text-center" style="position: center">
<select method="POST" typeof="submit" asp-page-handler="SelectedCalculation" id="dropdownSelected" name="SelectedCalculation">
<option style="display:none" value="value">Select a calculation type</option>
<option style="display:@Model.OptionTwoVisible; font-weight: bold;" value="OptionOne"> OptionOne </option>
<option style="display:@Model.UkOptionTwoVisible; font-weight: bold;" value=" OptionTwo ">OptionTwo</option>
<option style="display:@Model.OptionThreeVisible; font-weight: bold;" value="OptionThree"> OptionThree</option>
</select>
</div>
Handler and Ajax call:
(function ($) {
$(document).ready(function () {
$("#dropdownSelected").change(function () {
var selectedType= $("#dropdownSelected option:selected").val();
aj("Filter", "", selectedType);
})();
});
})(jQuery)
function aj(pageName, retFunc, args, failedCallBack) {
var retval;
retval = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: $(this).attr("formaction"),
data: args,
processData: false,
dataType: "json",
success: retFunc,
error: function (a, b, c) {
failedCallBack(a, b, c);
}
});
}
Filter.cshtml.cs (where I want to return the value from ajax call):
public ActionResult OnPostSelectedCalculation(string data)
{
var t = new JsonResult(data);
return new JsonResult(data);
}
I think you are missing json parsing
on data: JSON.stringify(YourParam),
So I would suggest to submit request on following format.
var args = {
key_1: "Value_1",
key_2: "Value_2"
}
$.ajax({
type: "POST",
url: $(this).attr("formaction"),
data: JSON.stringify(args),
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log(data);
}
});
Hope this would help.