0

I am new to Asp.net and currently I want to pass some parameter (selected user Id list) to the controller when user click the action link button, below is the action link code,

@Html.ActionLink("Edit Selected", "EditSelected", new { selectedUserIds = @Model.GetSelectedUserIds() })

The action in the controller is as below

// GET: 
    public async Task<ActionResult> EditSelected(List<string> selectedUserIds)
    {

But I found that the ActionLink is just compile when page is loaded and the selectedUserIds parameter will not be updated when I click this link button, so how can I handle this?

Carlos Liu
  • 2,348
  • 3
  • 37
  • 51
  • 1
    If the user is going to select the ids on the client, then you might need to use javascript to update. – Captain0 Mar 23 '16 at 09:58

4 Answers4

2

If you want to use a hyperlink for this you can do the following

public async Task<ActionResult> EditSelected(string selectedUserIds)
{
  var values = selectedUserIds.Split(',');
  //the rest of your code
}

Then add the following javascript.

 $(document).on('click', '.myLink', function(e) {
            e.preventDefault();

            //code to get all the selected values...
            var selectedUserIds = ['value1','value2'];

            window.location = $(this).attr('href') + '?selectedUserIds=' + selectedUserIds;
        });

And change the Html.ActionLink to

@Html.ActionLink("ClickMe", "EditSelected",null,new {@class="myLink"})
Captain0
  • 2,583
  • 2
  • 28
  • 44
1

You can make an ajax call to the required function.

A possible code sample is

<Section onclick="MyFunction()">Edit Selected</section>

<script>
function MyFunction(){
    $.Ajax({
             url:'http://localhost/controller/EditSelected',
             data: {
                   SelectedUserIds: @Model.GetSelectedUserIds();
                   },
             success:'http://....'
          })
}

See this post for more detail

Ajax Call

Community
  • 1
  • 1
It's a trap
  • 1,333
  • 17
  • 39
  • [Are answers that just contain links elsewhere really “good answers”?](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers) – CodeCaster Mar 23 '16 at 10:29
  • @RachitGupta it seems not work because I saw below codes when I 'view the source' of my page url: 'http://localhost/LicenseAssignment/EditSelected', data: { SelectedUserIds: System.Collections.Generic.List`1[System.String] }, and there is an error "Uncaught SyntaxError: Unterminated template literal" – Carlos Liu Mar 25 '16 at 01:54
  • Then you may have to pass individual properties of models and change the function definition accordingly. – It's a trap Mar 25 '16 at 03:16
0

You need to do a few things to get this to work!

I recommend you use the Form helper and post the Form to your action!

@using (Html.BeginForm("YourAction", "Yourcontroller", FormMethod.Post, new {your html attributes}))
    {...}

then you need something like that in your model:

public List<SelectListItem> IdList{ get; set; } // For your select list
public list<string> SelectedItems{get;set;} // Your selected Ids

In your controller you initialize and populate the list:

model.IdList = new List<SelectListItem>();
model.IdList.Add(new SelectListItem() { Text = "YourText", Value = "YourId" });

and so on...

In your form you need this:

@Html.ListBoxFor(m => m.SelectedItems, Model.IdList , new {@class = "form-control", id = "idList"})

Use a input type submit you post the form to your action.

the action needs the [HttpPost] Attribute and takes your Model as a parameter.

With the Model as a parameter you can do work with your list of selected Ids!

Nikolaj Zander
  • 1,270
  • 9
  • 13
  • In my case, I need select some users from the table and then I could either clicking the 'Edit Selected' or 'Deny Selected' (I have 2 possible actions for the selected users), so can I handle them in your way? – Carlos Liu Mar 24 '16 at 00:27
  • add a new property to your model. for example "string method {get;set;}" then use it with a hiddenfield, on your to buttons popullate the hiddenfield with on of two values (edit or delete) and submit the form afterwards. in the action you can check the hiddenfields value and do the appropriate action – Nikolaj Zander Mar 29 '16 at 15:02
0

Resolved by refer to Captain0's answer and this post (also refer to this post)

In the editor template, I attached user Id on the 'data' property of checkbox as below

<tr>
  <td style="text-align: center">
    @* Use below way instead of Html.CheckBox to attach the user Id to the data property
    and this will be parsed in the javascript to collect the selected user Id which will then be treat as parameter of action
    *@
    <input id="assignmentCheckBox" name="assignmentCheckBox" type="checkbox" data-userid=@Model.UserId value="true" />
    <input name="assignmentCheckBox" type="hidden" value="false" />
  </td>
  <td>
    @Html.DisplayFor(m => m.UserName)
  </td>

Then in the javascript I loop the checkboxes whose id is 'assignmentCheckBox' and is checked, then get the user Id data and put it to a array, at last jump to specified location by using the collected data as argument

@Html.ActionLink("Edit Selected", "GroupEdit", null, new { @class = "editSelectedLink" })

$(document).on('click', '.editSelectedLink', function(e) {
      //Cancel original submission
      e.preventDefault();

      //Build a collection of your objects
      var selectedUserIds = new Array();

      //Populate each of your checked values into the collection
      $('[id="assignmentCheckBox"]:checked').each(function() {
        selectedUserIds.push($(this).data('userid').toString());
      });

      window.location = $(this).attr('href') + '?selectedUserIds=' + selectedUserIds;
    });

And this is the corresponding Action method

public async Task<ActionResult> GroupEdit(string selectedUserIds)
{
      var userIds = selectedUserIds.Split(',');
      foreach (var userId in userIds)
      { . . .
Carlos Liu
  • 2,348
  • 3
  • 37
  • 51