Pass the value of ViewBag to the Jquery function as a parameter

When calling a js or jquery function, passing the ViewBag directly will prompt that the corresponding parameters are illegal.

@if (!string.IsNullOrEmpty(ViewBag.Message))
    {
        var messages = ViewBag.Message;
<script type="text/javascript">
    $(function () { p.success(ViewBag.Message); });

</script>
    }

The above code will display the following error:

Since the ViewBag is illegal, we can just convert it. I immediately thought of Json, tried several formats, and finally found that the Json.Serialize() method can meet our needs. This method is supported in .Net Core 3.1, .NET5, and .Net 6.

Then just pass the converted value to the function

    @if (!string.IsNullOrEmpty(ViewBag.Message))
    {

<script type="text/javascript">
    //序列化ViewBag
    var message = @Html.Raw(Json.Serialize(ViewBag.Message));
    $(function () { p.success(message); });

</script>
    }

For information on Json.Serialize, please refer to Microsoft's user manual.

How to serialize and deserialize JSON using C# - .NET | Microsoft Docs

 We run the modified jquery function. Success.ing!!

Guess you like

Origin blog.csdn.net/weixin_43604220/article/details/123650769