Burdy
Burdy

Reputation: 113

How to pass an array from one view and action to another in ASP.NET MVC?

What I want to achieve: I want a feature that selects multiple records from the index page on my asp.net mvc website which are redirected to another webpage, where they can be bulk edited.

I am using checkboxes to do this, but I don't know how I can access the contents of this array from another action and view.

For now, this is the code that I have done:

The Index View:

@model IEnumerable<BulkDelete.Models.Employee>

@TempData["employeeIdsToDelete"];

    <div style="font-family:Arial">
        @using (Html.BeginForm("checking", "Home", FormMethod.Post))
        {
            <table class="table">
                <thead>
                    <tr>
                        <td>Checkbox<br /></td>

                        <th>Name</th>
                        <th>Gender</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody>

                    @foreach (var item in Model)
                    {
                        <tr>
                            <td><input type="checkbox" name="employeeIdsToDelete" id="employeeIdsToDelete" value="@item.ID" /></td>
                            <td>@item.Name</td>
                            <td>@item.Gender</td>
                            <td>@item.Email</td>
                        </tr>
                    }

                </tbody>
                <br />

            </table>
            <input type="submit" value="Delete selected employees" />


        }
    </div>

The Controller Actions:

  public class HomeController : Controller
    {
        SampleDBContext db = new SampleDBContext();
        public ActionResult Index()
        {
            return View(db.Employees.ToList()) ;
        }

      [HttpPost]
            public ActionResult UpdateMultipleRecords(IEnumerable<int> employeeIdsToUpdate)
        {
      
            return checking(employeeIdsToUpdate);
        }

  public ActionResult checking(IEnumerable<int>employeeIdsToUpdate)
        {

            foreach (var e in employeeIdsToUpdate)
            {
                Employee em = new Employee();
                em = db.Employees.Find(e);
                em.Name = ViewBag.Signature;

                db.Entry(em).State = EntityState.Modified;
                db.SaveChanges();

            }
            return View();
        }

Upvotes: 1

Views: 1146

Answers (3)

Imran
Imran

Reputation: 254

Here are some options for sending array from a View to some controller action:

  1. Post the form to your controller action
  2. Send ajax call to your controller action
  3. MVC Hyperlink pointing to your controller action

Here are some options for sending array from a controller action to some other controller action:

  1. Save data in TempData (its available across controllers)
  2. Save data in browser memory (Temp Storage)
  3. Save data in DB
  4. Save data in Session object
  5. Save data in Cache object

and Please dont forget to mark this as answer ... thanks

Upvotes: 0

Kawsar Hamid
Kawsar Hamid

Reputation: 514

Instead of posting to index page. post the form in another page.

@using (Html.BeginForm("{actionNameOfAnotherPage}", "{anotherPageControllerName}", FormMethod.Post))

As you are posting an array of data, Use array indexing for form inputs.

@{ var index = 0;}
@foreach (var item in Model) 
{
    <tr>
        <td><input type="checkbox" name="[@index]employeeIdsToDelete" class="mycheckbox" id="employeeIdsToDelete" value="@item.ID" /></td>                                    
        <td>@item.Name</td>
        <td>@item.Gender</td>
        <td>@item.Email</td>
    </tr>
    @{ 
        index++;
    }
}

Upvotes: 1

Burak
Burak

Reputation: 507

You can also send them as an Ajax call, and in this scenerio you can also do this without a form.

<div style="font-family:Arial">
            <table class="table">
                <thead>
                    <tr>
                        <td>Checkbox<br /></td>
                        <th>Name</th>
                        <th>Gender</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody>

                    @foreach (var item in Model)
                    {
                        <tr>
                            <td><input type="checkbox" name="employeeIdsToDelete" class="mycheckbox" id="employeeIdsToDelete" value="@item.ID" /></td>
                            <td>@item.Name</td>
                            <td>@item.Gender</td>
                            <td>@item.Email</td>
                        </tr>
                    }

                </tbody>
                <br />

            </table>
            <input type="button" onClick="deleteEmployees()" value="Delete selected employees" />
</div>

and below your html page

<script>
function deleteEmployees() {
        var checkboxes = document.getElementsByClassName("mycheckbox");

        var checkedValues = [];

        for (var i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i].checked) {
                console.log(i);
                checkedValues.push(checkboxes[i].value)
            }
        }
        console.log(checkedValues);

        $.ajax({
            type: "POST",
            url: '@Url.Action("YourAction", "YourController")',
            data: { employeeIdsToUpdate: checkedValues },
            success: function (res) {
                if (res.ok) {
                    window.location = res.returnURL;
                }
            },
            error: function (req, status, error) {
                console.log(error);
            }
        });
    }
</script>

and in your POST ACTION you can take these values

[POST]
public ActionResult UpdateEmployees(int[] employeeIdsToUpdate)
{

            foreach (int e in employeeIdsToUpdate)
            {
                Employee em = new Employee();
                em = db.Employees.Find(e);
                em.Name = ViewBag.Signature;

                db.Entry(em).State = EntityState.Modified;
                db.SaveChanges();

            }
                            return Json(new { ok = true, returnURL = Url.Action(nameof("YOUR VIEW IN HERE"))});

}

Upvotes: 0

Related Questions