Home » c# » asp.net mvc – ASP.MVC model to JS object and back to C#-Exceptionshub

asp.net mvc – ASP.MVC model to JS object and back to C#-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I’m trying to replace server side action call by javascript action call.

I have action in controller

public ActionResult MyTest(TestObj obj)
{
return PartialView("test2");
}

And my action call in view looks like this right now:

<div id="TestDiv">
    @Html.Action("MyTest", "Home", new { obj = Model })
</div>

So i tried to replace it by this js function

<script>
    var jsModel [email protected](Json.Encode(Model));   @*'@serializer.Serialize(Model)';*@
    function newHope() {
        var url = '@Url.Action("MyTest", "Home")';
        $('#TestDiv').load(url, { obj: jsModel });

    }
</script>

However all obj properies have default values when I’m sending obj via js and everything is OK when it’s send from @Html.Action

Any idea why biding not working with js model?

How to&Answers:

Try doing this:

<script>
    var jsModel [email protected](Json.Encode(Model));   @*'@serializer.Serialize(Model)';*@
    function newHope() {
        var url = '@Url.Action("MyTest", "Home")';
        $('#TestDiv').load(url, '{ obj: ' +jsModel +'}');

    }
</script>

You need to stringify the entire payload so that it can be deserialezed properly. I have not tried it, so you might need to tweak it a bit.