How can I access a JsonResult variable in my code behind file from the javascript of my view? Razor Pages. C#

Viewed 58

Context: I am trying to pass a nested JSON object from my code behind page to a method in the .js in my view.

UI Flow: The user selects an organization from a ddl, then the ddl's onchange function is called, onchange function clicks the hidden submit button, code behind method is called which creates the nested json object with the needed organizational data.

1 Answers

Lessons Learned: I wasted too much time trying to make this happen via ajax. It is possible (maybe preferred) to use ajax to achieve my goal. If my page handler had been a get method, ajax would have been a quick solution. However, ajax in razor pages required a hidden field to contain the anti-forgery token for ajax posts. So why not use the razor page form to accomplish the same thing? This allows me to keep consistency throughout my application.

Notes: Please comment if there is a better way to do this. I used the form with the hidden submit button because it is what I could do quickly.

Solution:

  1. Put ddl in a form.
<form asp-page-handler="DdlValueSelected">
    <div class="form-group">
        <label>Select Me</label>
        <select class="form-control" onchange="ddlChanged()" asp-for="@Model.blah" asp- 
        items="@Model.blah"> 
        </select>        
    </div>
    <button hidden type="submit" id="ddlSubmitButton"></button>
</form>
  1. Have the onchange method in your .js click the hidden submit button in the form.
function ddlChanged() {
    $('#ddlSubmitButton').click();
}

3a. In your code behind method, make service call to return the object you need. 3b. Convert object to object type of JsonResult.

public async Task<IActionResult> OnPostDdlValueSelected(string ddlValue) 
{
   DataNeededAsJsonObject = await _service.GetDataNeededAsJsonObject(ddlValue);
   ConvertedDataNeededAsJsonObject = new JsonResult(DataNeededAsJsonObject);
   return Page();
}
  1. Access your code behind variable of type JsonResult by using @Json.Serialize(object) in your .js in your view.
function getJsonData() {
    jsonData = @Json.Serialize(Model.ConvertedDataNeededAsJsonObject);
    console.log(jsonData);
}

I welcome feedback, so I can do it better next time.

Related