Can i access MVC model properties in a separate js file referenced in the .cshtml fileHow can I upload files asynchronously?Can an ASP.NET MVC controller return an Image?How to change a model property from a javascript function inside a view?File Upload ASP.NET MVC 3.0How should a model be structured in MVC?Separation of business logic and data access in djangoBest pratice for completing MVC model properties which aren't bound?Jquery Set Bound Model Property MVCAccess ViewData & Session Variable in JS FileBinding ASP.Net MVC model with dates in custom format
What should I discuss with my DM prior to my first game?
What would prevent chimeras from reproducing with each other?
Why is Na5 not played in this line of the French Defense, Advance Variation?
Can we completely replace inheritance using strategy pattern and dependency injection?
How to write sign "|" (or) in LaTeX?
Use 1 9 6 2 in this order to make 75
What is the reason for setting flaps 1 on the ground at high temperatures?
The origin of the Russian proverb about two hares
Can a human be transformed into a Mind Flayer?
Can the removal of a duty-free sales trolley result in a measurable reduction in emissions?
Why Does Mama Coco Look Old After Going to the Other World?
How to avoid typing 'git' at the begining of every Git command
How can I remove material from this wood beam?
Diatonic chords of a pentatonic vs blues scale?
How durable are silver inlays on a blade?
Why is the length of the Kelvin unit of temperature equal to that of the Celsius unit?
Could a person damage a jet airliner - from the outside - with their bare hands?
Was planting UN flag on Moon ever discussed?
Housemarks (superimposed & combined letters, heraldry)
How do free-speech protections in the United States apply in public to corporate misrepresentations?
The significance of kelvin as a unit of absolute temperature
Strange outlet behavior
Latex - unable to get proper boxes
Why do radiation hardened IC packages often have long leads?
Can i access MVC model properties in a separate js file referenced in the .cshtml file
How can I upload files asynchronously?Can an ASP.NET MVC controller return an Image?How to change a model property from a javascript function inside a view?File Upload ASP.NET MVC 3.0How should a model be structured in MVC?Separation of business logic and data access in djangoBest pratice for completing MVC model properties which aren't bound?Jquery Set Bound Model Property MVCAccess ViewData & Session Variable in JS FileBinding ASP.Net MVC model with dates in custom format
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I am working on an MVC project which uses model binding. I need to access the whole model in a javascript file which is referenced in the view page.
I tried JSON encoding the whole model inside a script tag in the view page.
var model = @Html.Raw(Json.Encode(Model));
console.log(model);
which works fine.
In my case, the entire script has to stay in a separate page ie. Not inside the view page itself. How can I access the entire model from that script page?
A single property can be bound to a hidden input field, and the value can be accessed from js by its id i.e.:
<input type="hidden" id="modelObject" value="@model.property")/>
var model = $("#modelObject").val();
I need the whole model in the js page. How can this can be achieved?.
Thanks in Advance.
jquery asp.net asp.net-mvc model-view-controller model-binding
add a comment |
I am working on an MVC project which uses model binding. I need to access the whole model in a javascript file which is referenced in the view page.
I tried JSON encoding the whole model inside a script tag in the view page.
var model = @Html.Raw(Json.Encode(Model));
console.log(model);
which works fine.
In my case, the entire script has to stay in a separate page ie. Not inside the view page itself. How can I access the entire model from that script page?
A single property can be bound to a hidden input field, and the value can be accessed from js by its id i.e.:
<input type="hidden" id="modelObject" value="@model.property")/>
var model = $("#modelObject").val();
I need the whole model in the js page. How can this can be achieved?.
Thanks in Advance.
jquery asp.net asp.net-mvc model-view-controller model-binding
is my answer usefull for you?
– Daniël Tulp
Mar 24 at 20:25
check out thesrcattribute of thescriptelement.
– Sam Axe
Mar 24 at 21:05
add a comment |
I am working on an MVC project which uses model binding. I need to access the whole model in a javascript file which is referenced in the view page.
I tried JSON encoding the whole model inside a script tag in the view page.
var model = @Html.Raw(Json.Encode(Model));
console.log(model);
which works fine.
In my case, the entire script has to stay in a separate page ie. Not inside the view page itself. How can I access the entire model from that script page?
A single property can be bound to a hidden input field, and the value can be accessed from js by its id i.e.:
<input type="hidden" id="modelObject" value="@model.property")/>
var model = $("#modelObject").val();
I need the whole model in the js page. How can this can be achieved?.
Thanks in Advance.
jquery asp.net asp.net-mvc model-view-controller model-binding
I am working on an MVC project which uses model binding. I need to access the whole model in a javascript file which is referenced in the view page.
I tried JSON encoding the whole model inside a script tag in the view page.
var model = @Html.Raw(Json.Encode(Model));
console.log(model);
which works fine.
In my case, the entire script has to stay in a separate page ie. Not inside the view page itself. How can I access the entire model from that script page?
A single property can be bound to a hidden input field, and the value can be accessed from js by its id i.e.:
<input type="hidden" id="modelObject" value="@model.property")/>
var model = $("#modelObject").val();
I need the whole model in the js page. How can this can be achieved?.
Thanks in Advance.
jquery asp.net asp.net-mvc model-view-controller model-binding
jquery asp.net asp.net-mvc model-view-controller model-binding
edited Mar 19 at 13:47
Yadukrishnan M
asked Mar 19 at 12:35
Yadukrishnan MYadukrishnan M
8611
8611
is my answer usefull for you?
– Daniël Tulp
Mar 24 at 20:25
check out thesrcattribute of thescriptelement.
– Sam Axe
Mar 24 at 21:05
add a comment |
is my answer usefull for you?
– Daniël Tulp
Mar 24 at 20:25
check out thesrcattribute of thescriptelement.
– Sam Axe
Mar 24 at 21:05
is my answer usefull for you?
– Daniël Tulp
Mar 24 at 20:25
is my answer usefull for you?
– Daniël Tulp
Mar 24 at 20:25
check out the
src attribute of the script element.– Sam Axe
Mar 24 at 21:05
check out the
src attribute of the script element.– Sam Axe
Mar 24 at 21:05
add a comment |
2 Answers
2
active
oldest
votes
Razor templates output text, which can typically be a "page" (html/css/js) served with a content type of text/html. But you can serve other content types, like text/javascript, if you want.
First, create a controller action decorated with the ActionName attribute:
public class ScriptsController
[ActionName("model.js")]
public ActionResult ModelJs()
var model = new Object(); // your actual model here.
return View();
Then you create your view, which is just like your script tag in your current page:
var model = @Html.Raw(Json.Encode(Model));
make sure you remove the script element from your current page.
Then reference the new js view in your page:
<script type="text/javascript" src="@Url.Action("model.js", "Scripts")"></script>
better to return Json from the controller instead of converting it with .Raw and Encode to Json in the view
– Daniël Tulp
Mar 25 at 8:40
"Better" must always be defined.
– Sam Axe
Mar 26 at 9:12
I am just always very hesitant to using Html.Raw as it renders unencoded data in the view, of course you have covered this with the Json.Encode, but why not just do that encoding on the server and pass the pure Json to the client, looks like a better separation of concerns to me, and it also makes sure developers do not use Html.Raw incorrectly/insecure when you just agree not to use it at all.
– Daniël Tulp
Mar 27 at 9:46
I think either method will work fine. Returning json from the controller is great for the simplicity. Returning json from the view is great if you need to customize what gets returned.. like say, add some functions to the file, or encapsulate the json in a function. Either way, what I most disagree with is the idea that just because something has the potential for misuse people believe it shouldn't be used at all. Dangerous things should be used appropriately, and not misused. ButHtml.Rawhas a purpose and an acceptable use.
– Sam Axe
Mar 27 at 20:52
add a comment |
You can create a constructor for your JavasScript model and then instantiate that with razor code.
For example:
Model
public class Car
public string Brand get; set;
public string Fuel get; set;
Javascript file in module pattern, but you can use something else as well:
var car = (function(jsonModel)
var runs = "My " + jsonModel.Brand + " runs on " + jsonModel.Fuel;
return
Runs : runs
);
Razor view
@model Car
<!--load the javascript file somewhere-->
<script type="text/javascript">
$(function()
var myFord = new car(@Html.Raw(Json.Encode(@Model)) );
alert(myFord.Runs);
);
</script>
.NET fiddle I could not add an external javascript file, but you will probably get the point
Although I should say that using @Html.Raw is not recommended as it makes you vulnerable to XSS attacks (read more on the internet after a search). It is better to return the JSON object from your controller.
Edit
Here is an example how to use the JsonResult on .Net fiddle
controller
[HttpGet]
public JsonResult Car()
return Json(new Car("ford","gasoline"), JsonRequestBehavior.AllowGet);
razor view JS to get the json result and instantiate your JS module
$(function()
var model = $.ajax(
url: "@Url.Action("Car","Home")",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
).done(function(response)
console.log(response);
var myFord = new car(response);
alert(myFord.Runs);
);
);
This answer does not address the OPs question.
– Sam Axe
Mar 24 at 21:06
I think it does, as I read it the OP wants to have an entire model send to a JS file, as I mentioned I could not reference a separate file, that is why the JavaScript was inline in the Razor view, but you can of course place this in a separate file and then include the file from the view
– Daniël Tulp
Mar 25 at 8:38
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55241236%2fcan-i-access-mvc-model-properties-in-a-separate-js-file-referenced-in-the-cshtm%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Razor templates output text, which can typically be a "page" (html/css/js) served with a content type of text/html. But you can serve other content types, like text/javascript, if you want.
First, create a controller action decorated with the ActionName attribute:
public class ScriptsController
[ActionName("model.js")]
public ActionResult ModelJs()
var model = new Object(); // your actual model here.
return View();
Then you create your view, which is just like your script tag in your current page:
var model = @Html.Raw(Json.Encode(Model));
make sure you remove the script element from your current page.
Then reference the new js view in your page:
<script type="text/javascript" src="@Url.Action("model.js", "Scripts")"></script>
better to return Json from the controller instead of converting it with .Raw and Encode to Json in the view
– Daniël Tulp
Mar 25 at 8:40
"Better" must always be defined.
– Sam Axe
Mar 26 at 9:12
I am just always very hesitant to using Html.Raw as it renders unencoded data in the view, of course you have covered this with the Json.Encode, but why not just do that encoding on the server and pass the pure Json to the client, looks like a better separation of concerns to me, and it also makes sure developers do not use Html.Raw incorrectly/insecure when you just agree not to use it at all.
– Daniël Tulp
Mar 27 at 9:46
I think either method will work fine. Returning json from the controller is great for the simplicity. Returning json from the view is great if you need to customize what gets returned.. like say, add some functions to the file, or encapsulate the json in a function. Either way, what I most disagree with is the idea that just because something has the potential for misuse people believe it shouldn't be used at all. Dangerous things should be used appropriately, and not misused. ButHtml.Rawhas a purpose and an acceptable use.
– Sam Axe
Mar 27 at 20:52
add a comment |
Razor templates output text, which can typically be a "page" (html/css/js) served with a content type of text/html. But you can serve other content types, like text/javascript, if you want.
First, create a controller action decorated with the ActionName attribute:
public class ScriptsController
[ActionName("model.js")]
public ActionResult ModelJs()
var model = new Object(); // your actual model here.
return View();
Then you create your view, which is just like your script tag in your current page:
var model = @Html.Raw(Json.Encode(Model));
make sure you remove the script element from your current page.
Then reference the new js view in your page:
<script type="text/javascript" src="@Url.Action("model.js", "Scripts")"></script>
better to return Json from the controller instead of converting it with .Raw and Encode to Json in the view
– Daniël Tulp
Mar 25 at 8:40
"Better" must always be defined.
– Sam Axe
Mar 26 at 9:12
I am just always very hesitant to using Html.Raw as it renders unencoded data in the view, of course you have covered this with the Json.Encode, but why not just do that encoding on the server and pass the pure Json to the client, looks like a better separation of concerns to me, and it also makes sure developers do not use Html.Raw incorrectly/insecure when you just agree not to use it at all.
– Daniël Tulp
Mar 27 at 9:46
I think either method will work fine. Returning json from the controller is great for the simplicity. Returning json from the view is great if you need to customize what gets returned.. like say, add some functions to the file, or encapsulate the json in a function. Either way, what I most disagree with is the idea that just because something has the potential for misuse people believe it shouldn't be used at all. Dangerous things should be used appropriately, and not misused. ButHtml.Rawhas a purpose and an acceptable use.
– Sam Axe
Mar 27 at 20:52
add a comment |
Razor templates output text, which can typically be a "page" (html/css/js) served with a content type of text/html. But you can serve other content types, like text/javascript, if you want.
First, create a controller action decorated with the ActionName attribute:
public class ScriptsController
[ActionName("model.js")]
public ActionResult ModelJs()
var model = new Object(); // your actual model here.
return View();
Then you create your view, which is just like your script tag in your current page:
var model = @Html.Raw(Json.Encode(Model));
make sure you remove the script element from your current page.
Then reference the new js view in your page:
<script type="text/javascript" src="@Url.Action("model.js", "Scripts")"></script>
Razor templates output text, which can typically be a "page" (html/css/js) served with a content type of text/html. But you can serve other content types, like text/javascript, if you want.
First, create a controller action decorated with the ActionName attribute:
public class ScriptsController
[ActionName("model.js")]
public ActionResult ModelJs()
var model = new Object(); // your actual model here.
return View();
Then you create your view, which is just like your script tag in your current page:
var model = @Html.Raw(Json.Encode(Model));
make sure you remove the script element from your current page.
Then reference the new js view in your page:
<script type="text/javascript" src="@Url.Action("model.js", "Scripts")"></script>
answered Mar 24 at 21:15
Sam AxeSam Axe
27.5k74575
27.5k74575
better to return Json from the controller instead of converting it with .Raw and Encode to Json in the view
– Daniël Tulp
Mar 25 at 8:40
"Better" must always be defined.
– Sam Axe
Mar 26 at 9:12
I am just always very hesitant to using Html.Raw as it renders unencoded data in the view, of course you have covered this with the Json.Encode, but why not just do that encoding on the server and pass the pure Json to the client, looks like a better separation of concerns to me, and it also makes sure developers do not use Html.Raw incorrectly/insecure when you just agree not to use it at all.
– Daniël Tulp
Mar 27 at 9:46
I think either method will work fine. Returning json from the controller is great for the simplicity. Returning json from the view is great if you need to customize what gets returned.. like say, add some functions to the file, or encapsulate the json in a function. Either way, what I most disagree with is the idea that just because something has the potential for misuse people believe it shouldn't be used at all. Dangerous things should be used appropriately, and not misused. ButHtml.Rawhas a purpose and an acceptable use.
– Sam Axe
Mar 27 at 20:52
add a comment |
better to return Json from the controller instead of converting it with .Raw and Encode to Json in the view
– Daniël Tulp
Mar 25 at 8:40
"Better" must always be defined.
– Sam Axe
Mar 26 at 9:12
I am just always very hesitant to using Html.Raw as it renders unencoded data in the view, of course you have covered this with the Json.Encode, but why not just do that encoding on the server and pass the pure Json to the client, looks like a better separation of concerns to me, and it also makes sure developers do not use Html.Raw incorrectly/insecure when you just agree not to use it at all.
– Daniël Tulp
Mar 27 at 9:46
I think either method will work fine. Returning json from the controller is great for the simplicity. Returning json from the view is great if you need to customize what gets returned.. like say, add some functions to the file, or encapsulate the json in a function. Either way, what I most disagree with is the idea that just because something has the potential for misuse people believe it shouldn't be used at all. Dangerous things should be used appropriately, and not misused. ButHtml.Rawhas a purpose and an acceptable use.
– Sam Axe
Mar 27 at 20:52
better to return Json from the controller instead of converting it with .Raw and Encode to Json in the view
– Daniël Tulp
Mar 25 at 8:40
better to return Json from the controller instead of converting it with .Raw and Encode to Json in the view
– Daniël Tulp
Mar 25 at 8:40
"Better" must always be defined.
– Sam Axe
Mar 26 at 9:12
"Better" must always be defined.
– Sam Axe
Mar 26 at 9:12
I am just always very hesitant to using Html.Raw as it renders unencoded data in the view, of course you have covered this with the Json.Encode, but why not just do that encoding on the server and pass the pure Json to the client, looks like a better separation of concerns to me, and it also makes sure developers do not use Html.Raw incorrectly/insecure when you just agree not to use it at all.
– Daniël Tulp
Mar 27 at 9:46
I am just always very hesitant to using Html.Raw as it renders unencoded data in the view, of course you have covered this with the Json.Encode, but why not just do that encoding on the server and pass the pure Json to the client, looks like a better separation of concerns to me, and it also makes sure developers do not use Html.Raw incorrectly/insecure when you just agree not to use it at all.
– Daniël Tulp
Mar 27 at 9:46
I think either method will work fine. Returning json from the controller is great for the simplicity. Returning json from the view is great if you need to customize what gets returned.. like say, add some functions to the file, or encapsulate the json in a function. Either way, what I most disagree with is the idea that just because something has the potential for misuse people believe it shouldn't be used at all. Dangerous things should be used appropriately, and not misused. But
Html.Raw has a purpose and an acceptable use.– Sam Axe
Mar 27 at 20:52
I think either method will work fine. Returning json from the controller is great for the simplicity. Returning json from the view is great if you need to customize what gets returned.. like say, add some functions to the file, or encapsulate the json in a function. Either way, what I most disagree with is the idea that just because something has the potential for misuse people believe it shouldn't be used at all. Dangerous things should be used appropriately, and not misused. But
Html.Raw has a purpose and an acceptable use.– Sam Axe
Mar 27 at 20:52
add a comment |
You can create a constructor for your JavasScript model and then instantiate that with razor code.
For example:
Model
public class Car
public string Brand get; set;
public string Fuel get; set;
Javascript file in module pattern, but you can use something else as well:
var car = (function(jsonModel)
var runs = "My " + jsonModel.Brand + " runs on " + jsonModel.Fuel;
return
Runs : runs
);
Razor view
@model Car
<!--load the javascript file somewhere-->
<script type="text/javascript">
$(function()
var myFord = new car(@Html.Raw(Json.Encode(@Model)) );
alert(myFord.Runs);
);
</script>
.NET fiddle I could not add an external javascript file, but you will probably get the point
Although I should say that using @Html.Raw is not recommended as it makes you vulnerable to XSS attacks (read more on the internet after a search). It is better to return the JSON object from your controller.
Edit
Here is an example how to use the JsonResult on .Net fiddle
controller
[HttpGet]
public JsonResult Car()
return Json(new Car("ford","gasoline"), JsonRequestBehavior.AllowGet);
razor view JS to get the json result and instantiate your JS module
$(function()
var model = $.ajax(
url: "@Url.Action("Car","Home")",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
).done(function(response)
console.log(response);
var myFord = new car(response);
alert(myFord.Runs);
);
);
This answer does not address the OPs question.
– Sam Axe
Mar 24 at 21:06
I think it does, as I read it the OP wants to have an entire model send to a JS file, as I mentioned I could not reference a separate file, that is why the JavaScript was inline in the Razor view, but you can of course place this in a separate file and then include the file from the view
– Daniël Tulp
Mar 25 at 8:38
add a comment |
You can create a constructor for your JavasScript model and then instantiate that with razor code.
For example:
Model
public class Car
public string Brand get; set;
public string Fuel get; set;
Javascript file in module pattern, but you can use something else as well:
var car = (function(jsonModel)
var runs = "My " + jsonModel.Brand + " runs on " + jsonModel.Fuel;
return
Runs : runs
);
Razor view
@model Car
<!--load the javascript file somewhere-->
<script type="text/javascript">
$(function()
var myFord = new car(@Html.Raw(Json.Encode(@Model)) );
alert(myFord.Runs);
);
</script>
.NET fiddle I could not add an external javascript file, but you will probably get the point
Although I should say that using @Html.Raw is not recommended as it makes you vulnerable to XSS attacks (read more on the internet after a search). It is better to return the JSON object from your controller.
Edit
Here is an example how to use the JsonResult on .Net fiddle
controller
[HttpGet]
public JsonResult Car()
return Json(new Car("ford","gasoline"), JsonRequestBehavior.AllowGet);
razor view JS to get the json result and instantiate your JS module
$(function()
var model = $.ajax(
url: "@Url.Action("Car","Home")",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
).done(function(response)
console.log(response);
var myFord = new car(response);
alert(myFord.Runs);
);
);
This answer does not address the OPs question.
– Sam Axe
Mar 24 at 21:06
I think it does, as I read it the OP wants to have an entire model send to a JS file, as I mentioned I could not reference a separate file, that is why the JavaScript was inline in the Razor view, but you can of course place this in a separate file and then include the file from the view
– Daniël Tulp
Mar 25 at 8:38
add a comment |
You can create a constructor for your JavasScript model and then instantiate that with razor code.
For example:
Model
public class Car
public string Brand get; set;
public string Fuel get; set;
Javascript file in module pattern, but you can use something else as well:
var car = (function(jsonModel)
var runs = "My " + jsonModel.Brand + " runs on " + jsonModel.Fuel;
return
Runs : runs
);
Razor view
@model Car
<!--load the javascript file somewhere-->
<script type="text/javascript">
$(function()
var myFord = new car(@Html.Raw(Json.Encode(@Model)) );
alert(myFord.Runs);
);
</script>
.NET fiddle I could not add an external javascript file, but you will probably get the point
Although I should say that using @Html.Raw is not recommended as it makes you vulnerable to XSS attacks (read more on the internet after a search). It is better to return the JSON object from your controller.
Edit
Here is an example how to use the JsonResult on .Net fiddle
controller
[HttpGet]
public JsonResult Car()
return Json(new Car("ford","gasoline"), JsonRequestBehavior.AllowGet);
razor view JS to get the json result and instantiate your JS module
$(function()
var model = $.ajax(
url: "@Url.Action("Car","Home")",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
).done(function(response)
console.log(response);
var myFord = new car(response);
alert(myFord.Runs);
);
);
You can create a constructor for your JavasScript model and then instantiate that with razor code.
For example:
Model
public class Car
public string Brand get; set;
public string Fuel get; set;
Javascript file in module pattern, but you can use something else as well:
var car = (function(jsonModel)
var runs = "My " + jsonModel.Brand + " runs on " + jsonModel.Fuel;
return
Runs : runs
);
Razor view
@model Car
<!--load the javascript file somewhere-->
<script type="text/javascript">
$(function()
var myFord = new car(@Html.Raw(Json.Encode(@Model)) );
alert(myFord.Runs);
);
</script>
.NET fiddle I could not add an external javascript file, but you will probably get the point
Although I should say that using @Html.Raw is not recommended as it makes you vulnerable to XSS attacks (read more on the internet after a search). It is better to return the JSON object from your controller.
Edit
Here is an example how to use the JsonResult on .Net fiddle
controller
[HttpGet]
public JsonResult Car()
return Json(new Car("ford","gasoline"), JsonRequestBehavior.AllowGet);
razor view JS to get the json result and instantiate your JS module
$(function()
var model = $.ajax(
url: "@Url.Action("Car","Home")",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
).done(function(response)
console.log(response);
var myFord = new car(response);
alert(myFord.Runs);
);
);
edited Mar 24 at 20:33
answered Mar 19 at 14:06
Daniël TulpDaniël Tulp
91921345
91921345
This answer does not address the OPs question.
– Sam Axe
Mar 24 at 21:06
I think it does, as I read it the OP wants to have an entire model send to a JS file, as I mentioned I could not reference a separate file, that is why the JavaScript was inline in the Razor view, but you can of course place this in a separate file and then include the file from the view
– Daniël Tulp
Mar 25 at 8:38
add a comment |
This answer does not address the OPs question.
– Sam Axe
Mar 24 at 21:06
I think it does, as I read it the OP wants to have an entire model send to a JS file, as I mentioned I could not reference a separate file, that is why the JavaScript was inline in the Razor view, but you can of course place this in a separate file and then include the file from the view
– Daniël Tulp
Mar 25 at 8:38
This answer does not address the OPs question.
– Sam Axe
Mar 24 at 21:06
This answer does not address the OPs question.
– Sam Axe
Mar 24 at 21:06
I think it does, as I read it the OP wants to have an entire model send to a JS file, as I mentioned I could not reference a separate file, that is why the JavaScript was inline in the Razor view, but you can of course place this in a separate file and then include the file from the view
– Daniël Tulp
Mar 25 at 8:38
I think it does, as I read it the OP wants to have an entire model send to a JS file, as I mentioned I could not reference a separate file, that is why the JavaScript was inline in the Razor view, but you can of course place this in a separate file and then include the file from the view
– Daniël Tulp
Mar 25 at 8:38
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55241236%2fcan-i-access-mvc-model-properties-in-a-separate-js-file-referenced-in-the-cshtm%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
is my answer usefull for you?
– Daniël Tulp
Mar 24 at 20:25
check out the
srcattribute of thescriptelement.– Sam Axe
Mar 24 at 21:05