1

I would like to pass my entire ViewModel from a .cshtml file into an External Javascript that is included in the same cshtml file.

I have tried different solutions but none of them work. I first started with reguarl js variable in cshtml file and passed it into the external js file. E.g for the below code when I click on the below button I get, Uncaught ReferenceError: myValue is not defined


 **- in test.cshtml file:**

<button onclick="testAlert()"></button>
<script language="text/javascript">
    var myValue = "myValue test";
</script>
<script src="~/js/test.js"></script>

**in test.js:**
/**
 *  This is a test alert function in external js.
 * */
function testAlert() {
    console.log(myValue);
}

The above is just a test for regular variables which if when it works, then I would like the below object in the external javascript like below.

***in test.cshtml:***
var customer = @Html.Raw(JsonConvert.SerializeObject(Model.CustomerDetails));
***Then in test.js***
function testAlert() {
    console.log(customer.Names.FirstName);
}
4
  • your code is completely correct, not sure why it does not work, though Commented Oct 26, 2020 at 5:52
  • @Vyas Senthil, any update? Does my reply or Seabizkit reply help you? Commented Oct 30, 2020 at 9:09
  • @BrandoZhang - Thanks for taking the time to help me out guys Also to Seabizkut. Really appreciate the help. But please look at my answer for what finally worked. Would still like to improve on it if possible. Commented Nov 2, 2020 at 1:38
  • Guys also how do I get the comments from the c# object into the json string, so that I can have intellisense on the javascript object when working on the external JS file? Commented Nov 3, 2020 at 0:17

3 Answers 3

1

As far as I know, if you want to pass the model to JS scripts, I suggest you could use @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(object model)) to convert the model to a json string as @Seabizkit suggests. Then you could convert this json to model in the js and read its property.

More details, you could refer to below codes: Model class:

public class Course
{
    public int CourseID { get; set; }
    public string Title { get; set; }
    public int Credits { get; set; }
    public string SemesterNumber { get; set; }
}

In your view set a button like below:

<input type="button" onclick="testAlert()" value="test" />

Then add a script at cshtml like below:

@section scripts{

    <script>
         // Notice: we should add '' between the html.raw to set it as a json string.
        var customer = '@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))';

    </script>
}

Then in the another js file add below codes:

Since my model is just a simple model like this to test, if you want to use my codes, you should modify it.

function testAlert() {
    console.log(customer);
    var ce = JSON.parse(customer);
    alert(ce.SemesterNumber);
}

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

i think.... you lookng for

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

so in your case something like

function testAlert() {
    var customer = @Html.Raw(JsonConvert.SerializeObject(Model.CustomerDetails));
    var customerJson = JSON.parse(customer);
    console.log(customerJson.Names.FirstName);
}

Comments

0

I got my own answer but was not fully satisfied with it yet, so didn't post until today. Need more refinement though.

test.cshtml:

@using Newtonsoft.Json;
<script type="text/cshtml">
viewmodel = @Html.Raw(JsonConvert.SerializeObject(Model));
</script>

test.js: at the top:

var viewmodel;

Only by doing this does it work correctly. Most similar to @brando Zang's answer except for the extra initializing part. Still not sure why it works without var or let in the main cshtml page.

Also, intellisense is not working yet on my external js file test.js. But thanks a ton to Brando Zang and Sea Bizkut for taking the time to help me out.

Some findings which will be useful for other people:

In default .net core mvc 3.1 , the default json is automatically converting viewmodel values to camelcase from pascal case, so using newtonsoft instead keeps default functionality and naming conventions. Can do it for default JSon parser itself in startup itself but it is a hassle, so using Newtonsoft instead.

  1. Also for enum values, it takes the value and not the string by default. so in the model. e.g in js object for CustomerType you will get 0,1,2 instead of Standard, Premium or VIP. so to fix it,

    (VB syntax below for enum - not able to show code indented properly in SO) Public Enum CustomerType Standard = 0 Premium = 1 VIP = 2 End Enum

TestModel.cs:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

[JsonConverter(typeof(StringEnumConverter))]
public CustomerType CustomerType;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.