I am trying to implement a form with a list of parameters which can be added and removed by the user. The catch is that I want to do this without javascipt. This is to be done in ASP.NET MVC 3.
I have a form like this (simplified code, so might not be quite right, it is just to illustrate what I have got):
@using (Html.BeginForm("New", "Films", FormMethod.Post, new { id = "NewFilmForm" }))
{
@if (Model.Any())
{
<!-- List of directors that have already been added -->
<div id="AddedDirectors">
@foreach (var director in Model)
{
<span>
@Html.Hidden("AddedDirectors", @director)
@Html.Raw(director)
<!-- JQuery button to remove director -->
<button class="deleteButton" type="button">x</button>
</span>
}
</div>
}
<!-- Interface for adding a new director -->
<div id="AddDirectorInterface">
<!-- Jquery show/hide add single director interface -->
<button type="button" id="AddDirectorButton">+   Add a director</button>
<div>
@Html.TextBox("AddDirector")
<!-- Post add button -->
<button name="SubmitButton" value="@Html.Encode(NewFilmActions.AddDirector)">Add</button>
</div>
</div>
<button type="submit" name="SubmitButton" value="@Html.Encode(NewFilmActions.Save)">Save film</button>
}
I have two submit buttons here. Which are handled via a switch statement in the controller and identified via the value attribute which is set based on the NewFilmActions Enum.
Pressing the button with the AddDirector value posts to the controller, adds the name entered in the AddDirector textbox to the model and returns the view with the form again, adding the name specified by the user to the list of directors which have already been added (see commented section).
I would like to add a button allowing me to delete names which have already been added by the user... I could put in one single button to delete all of them in one go very easily, but if posible I would like to add individual buttons. I can't figure out how to do it though.
One solution I can think 开发者_JS百科off would be to append the name to the value and then in the switch statement have a default and check if the value contains a specified enum value, but that sounds a little like a botched together approach.
Can anybody either tell me how to do this or point me to some tutorial/explanations on how to implement this?
Just to emphasize: I know this can easily be done using JS, but I am looking at doing this entirely serverside for basic functionality and for my personal education.
I think you should reduce the scope of your form so it doesn't include the list.
Then you can put delete forms within you for loop, as shown below;
@foreach (var director in Model)
{
<span>
@Html.Raw(director)
@using (Html.BeginForm("Delete", "Films", FormMethod.Post, new { id = director.Id })){ <button name "DeleteButton" value="Delete">Delete</button>}
</span>
}
An example of this is also shown in this blog
精彩评论