Reputation: 4503
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.
Upvotes: 1
Views: 439
Reputation: 125207
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.
Upvotes: 1