Reputation: 304
I have been using ViewModel's properties in jquery like this.Though it works well, I am only reading the values of properties. For setting the properties using jquery, I use hidden variables. Please tell me is this a good practise?
if ("@Model.IsTemplate" == "@bool.FalseString") {
$("#someButton").show();
if ("@Model.Active" == "@bool.TrueString") {
$("#activeschedulespan").show();
$("#inactiveschedulespan").hide();
}
PLease not that this works well but want to whether it is a good/bad practise. If bad, then alternatives are welcome.
Thanks
Upvotes: 0
Views: 2776
Reputation: 1038850
It's very bad practice. I wouldn't mix server side Razor code with javascript like that. I would simply JSON serialize the model (or only the properties I need) and then manipulate it directly:
<script type="text/javascript">
// we serialize the IsTemplate and Active properties of the model because we
// only need them in javascript, but if we needed other properties we could have
// included them as well or serialize the entire model
var model = @Html.Raw(Json.Encode(Model.Select(x => new { x.IsTemplate, x.Active })));
// now that we have the model javascript variable, let's manipulate it:
if (!model.IsTemplate) {
$('#someButton').show();
if (model.Active) {
$('#activeschedulespan').show();
$('#inactiveschedulespan').hide();
}
}
</script>
But hey, why do I get the impression that you are using javascript for something that should be done directly on the server side? In this particular example you are using javascript for showing/hiding stuff from your DOM based on values that you know on the server (your model). So you could completely get rid of this javascript and decide whether to include those sections in the DOM based on the properties of your model.
Upvotes: 1
Reputation: 3870
I dont think its a problem. Because the C# codes are compiled to text when rendered in browser. If you see your script in browser you will see something like this.
if ("True" == "True") {
$("#someButton").show();
if ("False" == "True") {
$("#activeschedulespan").show();
$("#inactiveschedulespan").hide();
}
Considered @Model.IsTemplate
= true and @Model.Active = false
You can use your browsers developers tool to see the script. Or simply see the source of the page and find the script.
Upvotes: 0