I have an array in my Controller that I'm passing over to my View, and (temporarily) I'm trying to console.log
some of the values in the array (just to make sure I passed the array over correctly.)
I'm trying to send it over with ViewData
and access it through Razor code, but Razor won't allow me to do any javascript functions (such as console.log
).
I've tried a few different solutions but can't come up with anything that works, this is the solution that got me the closest:
View
function logValues()
{
console.log("test");
@{var capacity = ViewData["Capacity"] as string[]; }
for (var i = 0; i < 5; i++)
{
console.log(capacity[i]);
}
}
Controller
var uspCapacity = from d in db.uspGetEventKillSheetDetailedReport(option, date)
select new
{
d.Capacity
};
var uspCapacityList = uspCapacity.ToList();
ViewData["Capacity"] = uspCapacityList;
The console will successfully log "Test" but cannot access my capacity variable.. because I'm defining it in Razor and trying to access it outside of Razor. How can I access it with Javascript commands?
You can convert the C# array to JSON and assign this to a JS variable:
<script>
var capacity = @Html.Raw(Json.Encode(ViewData["Capacity"]));
// now you can use capacity like any other JS variable...
for (var i = 0; i < capacity.length; i++) {
console.log(capacity[i]);
}
</script>
Json.Encode
is defined in System.Web.Helpers
and should be available in every MVC project.
Your current server code is setting a collection of anonymous objects to the viewdata dictionary. It is not an array of strings.
ViewData["Capacity"] = (from d in db.uspGetEventKillSheetDetailedReport(option, date)
select d.Capacity).ToList();
This should work, assuming this code is in a razor file
function logValues()
{
console.log("test");
var capacity = @Html.Raw(JsonConvert.SerializeObject(ViewData["Capacity"]))
for (var i = 0; i < 5; i++)
{
console.log(capacity[i]);
}
}
When razor executes the above code, it will serialize the string list we set to Viewdata dictionary to a string for the array initialization(ex: ["Java","Swift","SQL","PHP","Ruby"]
) and js will set that value to the capacity
variable
JsonConvert
is defined in the Newtonsoft.Json
namespace. So you need to import that to your razor view.
Try this:
function logValues()
{
console.log("test");
@{var capacity = (List<int>)ViewData["Capacity"]; }
@foreach (var s in capacity)
{
<text>console.log(@s)</text>
}
}
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.