SurajS
SurajS

Reputation: 497

Using a value from model and javascript together in MVC 4

I want to use a variable from model:

Model.ActionId

and a varialble from javascript (selected index of dropdown)

$("#ddlMethod").val()

together in a if condition.

I have tried:

@if (Model.ActionID== 0 && $("#ddlMethod").val()== 2)
        alert("yes");

another:

if (@Model.ActionID== 0 && $("#ddlMethod").val()== 2)
        alert("yes");

assigning the values first:

var selectedMethod = $("#ddlMethod").val();
    var actionId = @Model.ActionID;
    if (actionId == 0 && selectedMethod == 2)
        alert("yes");

None of them worked. Help.

enter image description here

Upvotes: 0

Views: 92

Answers (2)

Grundy
Grundy

Reputation: 13381

if your script in the page so you have a few way for use server variable in your client code:

  1. use directly

    if (@Model.ActionID == 0 && $("#ddlMethod").val()== '2')
        alert("yes");
    

    in this case it rendered for Model.ActionID = 0 like

    if (0 == 0 && $("#ddlMethod").val()== '2')
        alert("yes");
    
  2. render this script tag only for needed action id like

    @if (Model.ActionID == 0){
        <script type="text/javascript">
            if( $("#ddlMethod").val()== '2')
                alert("yes");
        </script>
    }
    

    in this case this sctipt rendered and executed only when Model.ActionID == 0

If your script in separated file then you again have a few way:

use hidden field as suggest @AmmarCSE, or save Model.ActionID to global varibale in your page

var modelActionId = @Model.ActionID

and use it in script

if (modelActionId == 0 && $("#ddlMethod").val()== '2')
    alert("yes");

NOTE: method val, in your case, return string rather than number

Upvotes: 1

AmmarCSE
AmmarCSE

Reputation: 30557

The simply way would be to put the model value in a hidden element like

<input type="hidden" value="@Model.ActionID" id="ActionID"/>

and then in your javascript

var selectedMethod = $("#ddlMethod").val();
var actionId = $("#ActionID").val();
if (actionId == 0 && selectedMethod == 2)
    alert("yes");

Update

if (@Model.ActionID== 0 && $("#ddlMethod").val()== 2)
        alert("yes");

will not work because you need to properly escape razor code when mixing with javascript by putting it in a code block

@{ ... } or @if, etc.

and putting the code itself in an escaped sequence

@: or the <text> tag.

Try

 @if (<text> '@Model.ActionID' </text> == 0 && $("#ddlMethod").val()== 2){
      <script>
                alert("yes");
      </script>
}

Upvotes: 1

Related Questions