简体   繁体   中英

How to read string message from ViewBag to Javascript object?

I have this action method which return error message and it did:

var content = responsePost.Content.ReadAsStringAsync().Result;
model = JsonConvert.DeserializeObject<MyAPIResponse>(content);
ViewBag.Message = model.message;

In my Razor view page, I try to read it with the following code:

@{ 
    var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
    var userInfoJson = jss.Serialize(ViewBag.Message);
}
<script>
    var errors = JSON.parse('@Html.Raw(userInfoJson)');
    $(document).ready(function () {
    for (var i = 0; i < errors.Count; i++)
    {

    }
});
</script>

But the output rendered back is:

<script>
    var errors = JSON.parse('"[\"Passwords must have at least one non letter or digit character. Passwords must have at least one lowercase (\u0027a\u0027-\u0027z\u0027). Passwords must have at least one uppercase (\u0027A\u0027-\u0027Z\u0027).\"]"');
    $(document).ready(function () {
    for (var i = 0; i < errors.Count; i++)
    {

    }
});
</script>

I am using C# MVC Razor for the UI and in my API is Identity for the password policy.

In the controller, just set the object in the bag:

public ActionResult Index()
{
    var errors = new[] { "error1", "error2" };
    ViewBag.Errors = errors;
    return View();
}

Then in view serialize and use it:

<script>
    var errors = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.Errors))
    errors.forEach(item => { alert(item);});
</script>

Note:

  • In case you don't have an array in the bag, for example ViewBag.Errors = "error1" , then don't use forEach , use alert(errors);

  • JSON.parse is unnecessary in this case. You are not receiving a string from server, you are rendering the html content and javascripts in the response.

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