3

I need to pass a model value item.ID to one of my javascript function how can I do that ?

I triedfunction("@item.ID") but its not working

2
  • Did you try with single quotes? Also please put some code over here/ Commented Sep 17, 2013 at 12:02
  • We need to see more code and what is your error exactly ? Commented Sep 17, 2013 at 12:03

4 Answers 4

4

It generally works this way, you just have to omit the "" otherwise it gets interpreted as string. So you can write something like that in your JS:

var myinteger = @item.ID;

which renders as

var myinteger = 123;   //for example

Edit: This makes sense when you id is an integer, of course, for strings you need to encapsulate it in '' or "". And don't get annoyed by any syntax errors reported by intellisense, it seems to have a problem with that but it works out just nicely.

Sign up to request clarification or add additional context in comments.

Comments

3

You can pass the model data into the java script file in these ways (1). Just set the value in hidden field and access the value of hidden field in java script. (2). And pass the value using function parameter. (3).

        var LoginResourceKeyCollection = {
            UserName_Required: '<%= Model.UserName%>',
            Password_Required: '<%= Model.Password%>'

        }
   </script>

Comments

3

Try this...mind single quotes on parameter value while calling js function

function MyJsFunction(modelvalue)
{
     alert("your model value: " + modelvalue);
}

<input type="button" onclick="MyJsFunction('@item.ID')" />
OR
<input type="button" onclick="MyJsFunction('@(item.ID)')" />

Comments

0

The best solution is pass your textbox ID to javascrpit function and then in function retrieve the value form the ID,

 @Html.TextBoxFor(model => model.DatemailedStart, new {id = "MailStartDate", placeholder = "MM/DD/YYYY", maxlength = "40", @class = "TextboxDates", @onblur = "isValidDate('MailStartDate');" })

  function isValidDate(id) {
    var dateString = $('#'+id+'').val();
  }

Comments

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.