asp .net mvc pass list of javascript object from view to controller without using ajax Edit

Murugan Andezuthu Dharmaratnam | 25 September 2020 | 676

In this post, we will look at how to pass a list of a javascript object from view to controller in asp .net MVC application. I wrote this article while I was writing the recipe edit code for 4beginner.com application. In recipe edit, I can add recipe ingredients, I am storing the list of objects in a javascript object array. When I click on save I have to pass the list of recipe ingredients to the controller. To pass the javascript objects to the controller we have to convert the object array to json.

Add Hidden Input Element

JSON can be passed to the controller using a hidden input field. When the user clicks on submit's the form the data in the input will be passed to the controller. Add a hidden input after Html.BeginForm()

@using (Html.BeginForm())
{
    <input id="jsonIngredients" name="jsonIngredients" type="hidden" />


call javascript objectToJson() function to copy json data to input

<input type="submit" value="Save" class="btn btn-normal" onclick="objectToJson()" />

Here is the objectToJson javascript function

<script type="text/javascript">
function objectToJson()
{
    $("#jsonIngredients").val(JSON.stringify(lstIngredients));
}
</script>

finally, receive the JSON as a string in the controller action method. I have also written the code to convert the JSON to C# list of objects.

public ActionResult Edit(Recipe recipe, String jsonDirections, String jsonIngredients)
{
  List<RecipeIngredientsSP> lstRecipeIngredientsSP = Newtonsoft.Json.JsonConvert.DeserializeObject<List<RecipeIngredientsSP>>(jsonIngredients);
}