Passing data from ViewModel to javascript
I've got an Ajax.BeginForm on my 开发者_开发技巧page which on success should run a javascript function. I've done that before and it has worked fine. However, in today's case I want to pass in my javascript function some variables that I get from my ViewModel:
My partial view:
@model MyProject.ViewModels.CategoryViewModel
@{
var hasLang = Model.Language != "" ? Model.Language : "-1";
}
<script type="text/javascript">
function UpdateCategoryProgress() {
console.log("this works");
console.log(@hasLang);
console.log("this doesn't works");
if (@hasLang == "-1") {
$.post('@Url.Action("CategoryProgress", "Home")', { categoryid: @(Model.Category.Id) }, function (data) {
populateDiv($("#CategoryProgressWrapper"), data);
});
}
else {
$.post('@Url.Action("CategoryProgress", "Home")', { categoryid: @(Model.Category.Id), lang: @(hasLang) }, function (data)
populateDiv($("#CategoryProgressWrapper"), data);
});
}
}
</script>
<div id="editingContainer">
@using (Ajax.BeginForm("Edit", new AjaxOptions { UpdateTargetId = "featuresDiv", OnSuccess = "UpdateCategoryProgress" }))
{
(code here)
)
Now to the interesting part, the code runs fine. The function is run on success however only the first console.log("this works") is displayed in the console. Everything after that is simply ignored.
I've tried using the hasLang variable because when I was running the following:
if (@Model.Language == "") {
$.post('@Url.Action("CategoryProgress", "Home")', { categoryid: @(Model.Category.Id) }, function (data) {
populateDiv($("#CategoryProgressWrapper"), data);
});
}
else {
$.post('@Url.Action("CategoryProgress", "Home")', { categoryid: @(Model.Category.Id), lang: @Model.Language }, function (data) {
populateDiv($("#CategoryProgressWrapper"), data);
});
}
I would get the error in the firebug console:
syntax error
if ( == "")
It was completely ignoring the @Model.Language
I've also tried passing the it with () like: @(hasLang)
or @(@Model.Language)
without success.
How can I pass my @Model.Language
to my jquery?
Thanks
You need to put Model.Language
in double-quotes to create a Javascript string literal.
You should also call Server.JavaScriptStringEncode
.
精彩评论