简体   繁体   中英

Passing a razor object to a javascript function

I have my JS function:

function LoadJs(hostApp) {
    $.ajax({
        type: "POST",
        url: '@Url.Action("LoadJs", "Home")',
        data: { "hostApp": hostApp },
        success: function (Js) {
            Response.Write(Js)   
        }
    });
}

When I call the function in my Summary.vbhtml file, I would like to pass it my hostApp object and then have the Javascript pass the object to a controller action.

Here is my script tag calling the LoadJs function:

<script type="text/javascript">    
    LoadJs( @(model)); 
</script>

I've tried '@model' , '@(model)' , and @model but nothing seems to pass it correctly. When I pass it the first two ways, it passes a string, which is not what I want and if I try the last way or the way in the example then it turned @model into the correct object, but it says it is undefined.

You can use

<script type="text/javascript">    
    LoadJs(@(Html.Raw(new JavaScriptSerializer().Serialize(model))));
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM