Aleksei Chepovoi
Aleksei Chepovoi

Reputation: 3955

How to assign c# guid value to javascript variable using razor viewmodel in asp.net mvc?

I have a view model with property of Guid type. I need to assign it to javascript object property and post this object to some action method.

When I write (in javascript):

var partyId = @Model.Id;  // "Id" is of Guid type

I get

var partyId = 6abbf77d-ba28-4d8a-87ff-2fa8f8a070c9;
// Uncaught SyntaxError: Unexpected identifier 

How can I handle this? I mean assign Id value to javascript variable.

Upvotes: 6

Views: 7307

Answers (4)

Adam Miller
Adam Miller

Reputation: 777

Enclose @Model.Id within quotes.

Upvotes: 8

ps2goat
ps2goat

Reputation: 8485

You can enclose the model with single or double quotes. You may receive weird parsing errors doing that, but you can typically get rid of them by enclosing the vb/c# code with parentheses.

var partyId = '@(Model.Id)';

Upvotes: 3

Grant Thomas
Grant Thomas

Reputation: 45058

Your JavaScript output is ultimately going to be a string, so it will formatted as such using quotes:

var partyId = '6abbf77d-ba28-4d8a-87ff-2fa8f8a070c9';

Your current snippet is missing this and is just rendering the raw value.

I'm unaware of any GUID type in JavaScript to parse it between, though, if that's what you're looking for.

Upvotes: 3

Ricky S
Ricky S

Reputation: 371

Enclose it in quotes?

var partyId = '@Model.Id';

Upvotes: 2

Related Questions