1

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();
        }
1
  • Another action = another request. There are obvious ways to pass data between requests: use session container at the server, use querystring, use cookie. In your case, I'd opt for the former. Commented Sep 17, 2020 at 8:20

3 Answers 3

1

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++;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

For some reason, there is no data when it is passed as you have showed me. It keeps saying null object reference
Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error: Line 30: Line 31: Line 32: foreach (var e in employeeIdsToUpdate) Line 33: { Line 34: Employee em = new Employee();
0

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"))});

}

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.