1

Just getting into JQuery and Asp.net MVC 2 and wanted to know how to pass variables from a loop to a javascript function.

So I have :

<% int i = 0; %>
<% foreach (var item in Model) { %>

    <tr>
        <td>
         <input type="button" id="btnSubmit" value="Save" onclick="javascript:updatePerson(i);" />
         <input type="text" id='<%= "persons[" + i + "].Name" %>'  name='<%= "persons[" + i + "].Name" %>' value='<%=item.Name %>' />
        </td>

    </tr>

    <% i++; %>
<% } %>

Clearly

onclick="javascript:updatePerson(i);"

is wrong.

How do I pass the variable i into the updatePerson function?

JD

4 Answers 4

2

I would recommend you taking a different, better approach as right now I see that you are mixing C#, javascript and HTML into the same page which results in what is called horrible tag soup.

So improvement number 1: use editor templates instead of those foreach loops. In your main view instead of writing what you've posted in your question simply:

<%= Html.EditorForModel() %>

and then define an editor template which will be called automatically for each element in your model collection (~/Views/Home/EditorTemplates/Person.ascx):

<%@ Control 
    Language="C#"
    Inherits="System.Web.Mvc.ViewUserControl<YourApp.Models.Person>" %>
<tr>
    <td>
        <% using (Html.BeginForm("Save", "Persons", 
            new { id = Model.Id }, FormMethod.Post, 
            new { @class = "saveform" })) { %>
            <%= Html.TextBoxFor(x => x.Name) %>
            <input type="submit" value="Save" />
        <% } %>
    </td>
</tr>

Notice that the name of the partial is the same as the type name to which it is strongly typed (Person.ascx). Also notice the location: ~/Views/Home/EditorTemplates where Home of course is the name of the current controller. It could also be placed in ~/Views/Shared/EditorTemplates if you wanted to reuse it between multiple controllers. And because the editor template is strongly typed to a view model you can use strongly typed helpers such as Html.TextBoxFor so that you don't have to manually hardcode names and values of the textboxes and wonder why does the model binder doesn't work correctly.

Improvement number 2: progressively enhance your markup with jquery in a separate javascript file:

$(function() {
    $('.saveform').submit(function() {
        // When the form is submitted
        // For example you could call the associated action using AJAX:
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function(result) {
                alert('successfully saved');
            }
        });
        return false; 
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. I have just started learning ASP.NET MVC2 and JQuery so I really appreciate the help you have provided. I will read more on templates and hopefully start to plug them in.
1

You can embed the current value of i in your Javascript expression in the same way you're doing it in the rest of your code:

<input type="button" id="btnSubmit" value="Save"
    onclick="updatePerson(<%= i %>);" />

1 Comment

Thanks Frederic, Omkar got in just before you but I did mark it up :)
1
onclick="javascript:updatePerson(<%=i%>);"

Should work

1 Comment

Thanks Omkar, just spent an hour looking and was about to give up.
0

Javascript is client side while asp is serverside. In other words:

  1. ASP generates html
  2. The HTML is sent to browser
  3. Your javascript is executed by the browser.

That's why your original code doesn't work. i do not exist in the generated html.

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.