简体   繁体   中英

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.

将@ Model.Id括在引号内。

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.

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)';

用引号括起来?

var partyId = '@Model.Id';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM