Member 13029506 Ответов: 1

Как передать массив в новое представление в ASP.NET MVC?


В приведенном ниже коде я создал представление индекса, которое позволяет пользователям проверять записи, которые они хотят обновить. При нажатии на кнопку Отправить они должны быть перенаправлены на веб-страницу, и для обновления этих записей необходимо выполнить некоторый код.

Ниже приведен код, который я реализовал:

вид
@model IEnumerable<BulkDelete.Models.Employee>

@{int[] employeesToUpdate;}


    <div style="font-family:Arial">
        @using (Html.BeginForm("UpdateMultiple", "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="employeesToUpdate" id="employeesToUpdate" value="@item.ID" />
                                
                            </td>
                            <td>@item.Name</td>
                            <td>@item.Gender</td>
                            <td>@item.Email</td>
                        </tr>
                    }

                </tbody>
               

            </table>

            <input type="submit"  value="update selected employees" />


        }
    </div>



контроллер:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BulkDelete.Models;
namespace BulkDelete.Controllers
{
    public class HomeController : Controller
    {
        SampleDBContext db = new SampleDBContext();
        public  System.Web.SessionState.HttpSessionState Session { get; }

        public ActionResult Index()
        {
            return View(db.Employees.ToList()) ;
        }


        [HttpPost]
        public ActionResult UpdateMultiple(IEnumerable<int> employeesToUpdate)
        {
            
            return RedirectToAction("UpdateMultipleRecords");
        }

        
        //[HttpPost]
        public ActionResult UpdateMultipleRecords()
        {

            IEnumerable<int> employeesToUpdate = (IEnumerable<int>)TempData["employeesToUpdate"];
            var listemployee = db.Employees.Where(x => employeesToUpdate.Contains(x.ID));
            foreach (var item in listemployee)
            {
                int itemid = item.ID;
                Employee e = db.Employees.Find(itemid);
                e.Email = "hello.";
               // e = db.Employees.Find(item);
                db.Entry(e).State = EntityState.Modified;
                
            }
            db.SaveChanges();
            return RedirectToAction("Index");
        }
}



Я продолжаю получать одну и ту же ошибку снова и снова, которая является :

Unable to create a null constant value of type 'System.Collections.Generic.IEnumerable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only entity types, enumeration types or primitive types are supported in this context.
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.NotSupportedException: Unable to create a null constant value of type 'System.Collections.Generic.IEnumerable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only entity types, enumeration types or primitive types are supported in this context.


Line 34:             IEnumerable<int> employeesToUpdate = (IEnumerable<int>)TempData["employeesToUpdate"];
Line 35:             var listemployee = db.Employees.Where(x => employeesToUpdate.Contains(x.ID));
Line 36:             foreach (var item in listemployee)
Line 37:             {
Line 38:                 int itemid = item.ID;


Что я уже пробовал:

Код работает, когда он просто выполняется с индексной страницы, но при перенаправлении на другую веб-страницу эта ошибка продолжает появляться

F-ES Sitecore

Гугл, Как пройти список или массив в контроллер, вы не можете использовать "по каждому элементу(ВАР х в модель)" в представлении, вы должны использовать "для" петли и при индексировании массива, но образцы вы найдете покажет вам, что нужно делать.

1 Ответов

Рейтинг:
8

Richard Deeming

Цитата:
[HttpPost]
public ActionResult UpdateMultiple(IEnumerable<int> employeesToUpdate)
{
    return RedirectToAction("UpdateMultipleRecords");
}

public ActionResult UpdateMultipleRecords()
{
    IEnumerable<int> employeesToUpdate = (IEnumerable<int>)TempData["employeesToUpdate"];
Вы не сохранили этот список в TempData коллекция в вашем распоряжении UpdateMultiple действие, так что employeesToUpdate переменная будет null В вашем UpdateMultipleRecords действие.
public ActionResult UpdateMultiple(IEnumerable<int> employeesToUpdate)
{
    TempData["employeesToUpdate"] = employeesToUpdate;
    return RedirectToAction("UpdateMultipleRecords");
}


Member 13029506

Спасибо, сработало отлично :)