How to pass a value to razor variable from javascript variable, is it possible asp.net mvc razor view engine?
@{
int a = 0;
}
Okay, so this question is old... but I wanted to do something similar and I found a solution that works for me. Maybe it might help someone else.
I have a List<QuestionType>
that I fill a drop down with. I want to put that selection into the QuestionType
property on the Question
object that I'm creating in the form. I'm using Knockout.js
for the select binding. This sets the self.QuestionType
knockout observable property to a QuestionType
object when the user selects one.
<select class="form-control form-control-sm"
data-bind="options: QuestionTypes, optionsText: 'QuestionTypeText', value: QuestionType, optionsCaption: 'Choose...'">
</select>
I have a hidden field that will hold this object:
@Html.Hidden("NewQuestion.QuestionTypeJson", Model.NewQuestion.QuestionTypeJson)
In the subscription for the observable, I set the hidden field to a JSON.stringify
-ed version of the object.
self.QuestionType.subscribe(function(newValue) {
if (newValue !== null && newValue !== undefined) {
document.getElementById('NewQuestion_QuestionTypeJson').value = JSON.stringify(newValue);
}
});
In the Question
object, I have a field called QuestionTypeJson
that is filled when the user selects a question type. I use this field to get the QuestionType
in the Question
object like this:
public string QuestionTypeJson { get; set; }
private QuestionType _questionType = new QuestionType();
public QuestionType QuestionType
{
get => string.IsNullOrEmpty(QuestionTypeJson) ? _questionType : JsonConvert.DeserializeObject<QuestionType>(QuestionTypeJson);
set => _questionType = value;
}
So if the QuestionTypeJson
field contains something, it will deserialize that and use it for QuestionType
, otherwise it'll just use what is in the backing field.
I have essentially 'passed' a JavaScript object to my model without using Razor
or an Ajax
call. You can probably do something similar to this without using Knockout.js
, but that's what I'm using so...