How to pass variable in jquery for loop variable
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开发者_C百科 + "].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
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;
});
});
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 %>);" />
onclick="javascript:updatePerson(<%=i%>);"
Should work
Javascript is client side while asp is serverside. In other words:
- ASP generates html
- The HTML is sent to browser
- Your javascript is executed by the browser.
That's why your original code doesn't work. i
do not exist in the generated html.
精彩评论