tags:

views:

35

answers:

2

Hello all,

I've got a form where users can edit members of a group.

So they have the possibilty to add members or remove existing members. So the Url goes like ".../Group/Edit/4" Where 4 is the id of the group.

the view looks like this

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm("AddUser", "Group")) %>
    <%{%>
        <label for="newUser">User</label>
        <%=Html.TextBox("username")%>
        <input type="submit" value="Add"/>
    </div>
    <%}%>

    <% using (Html.BeginForm("RemoveUser", "Group")) %>
    <%{%>
    <div class="inputItem">
        <label for="groupMember">Bestehende Mitglieder</label>
        <%= Html.ListBox("groupMember", from g in Model.GetMembers() select new SelectListItem(){Text = g}) %>
        <input type="submit" value="Remove" />
    </div>
    <%}%>
</asp:Content>

The problem is that after adding or removing one user i lose the id of the group. What is the best solution for solving this kind of problem? Should I use hidden fields to save the group id?

Thanks in advance.

+1  A: 

Hidden fields are a good way of persisting the id during posts.

Darin Dimitrov
A: 

You could use a hidden field or you could just parse the value into your route. I'm not sure how you're parsing the group id to the view but it would look something like:

<% using (Html.BeginForm("AddUser", "Group", new { groupId = Model.GroupID })) { %>

Then your controller will look something like this using the PRG pattern

[HttpGet]
public ViewResult Edit(int groupId) {
  //your logic here

  var model = new MyModel() {
    GroupID = groupId
  };
  return View("Edit", model);
}

[HttpPost]
public ActionResult AddUser(int groupId, string username) {
  //your logic here
  return RedirectToAction("Edit", new { GroupID = groupId });
}

[HttpPost]
public ActionResult RemoveUser(int groupId, string username) {
  //your logic here
  return RedirectToAction("Edit", new { GroupID = groupId });
}

The advantage to this method is that it's more RESTful

David G
hmm than i would jump to another view, but i want to stay in the edit view, where i can both delete and add members
nWorx
@nWorx You could just return your 'edit' view but it's better to follow the PRG pattern and redirect to your 'edit' Action. I've updated my answer with an example using PRG.
David G
cool thanks that seems to be what i was looking for, i'll check it and give you feedback
nWorx
aww :-( now if the username is invalid and i add ModelState.AddError() i doesn't get displayed. but if i use "return View("Edit", group)" the errors get displayed...is the concept of the page so wrong?
nWorx
@nWorx if the form has validation errors you return View("Edit" new { GroupID = groupId }) if the form is good then you perform your business logic and return RedirectToAction("Edit", new { GroupID = groupId })
David G