0

I am creating a web app in which, I want to pass model data into a Javascript function when user click a button,

Below is my code

<input type="button" id="btnNextAction" class="btn btn-primary" value="JSFunction" onclick="callJS('@Model.NextActionParam');" />

Javascript Function

function callJS(param) {

}

but the value of param is appears as projectName.Models.modelName.NextActionParam

model.NextActionParam is my model which contains some properties like name, id.etc

how can I get the model property with value in Javascript?

4
  • What Model.NextActionParam contains? Commented Mar 27, 2019 at 6:34
  • model properties Commented Mar 27, 2019 at 6:35
  • A Javascript function can’t possibly understand a .NET object if you don’t parse it in a way that JavaScript can understand (a literal object or a JSON string). Commented Mar 27, 2019 at 6:39
  • can you please show me one example Commented Mar 27, 2019 at 6:45

1 Answer 1

1

You need to convert Model.NextActionParam to JSON string with Json.Encode() method. Better way is put JSON inside <script> section and set some variable, then use it anywhere.

<script>
    var nextActionParam = @Html.Raw(Json.Encode(Model.NextActionParam));
</script>

<input type="button" id="btnNextAction" class="btn btn-primary" value="JSFunction"
onclick="callJS(nextActionParam)" />
Sign up to request clarification or add additional context in comments.

2 Comments

Tried this but getting error, Uncaught SyntaxError: Invalid or unexpected token onclick="callJS('{"NextAction":null,"RegId":459405,"CurrId":0,"SurveyId":203,"SurveyType":0,"WatchParameters":"hFlkVcpTCCoI2lnA"}');" />
If pass JSON string in attribute you need to escape " char. So, better replace this code in <script> section.

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.