【问题标题】:Returning array or List of models from form in Razor View to action on Submit从 Razor 视图中的表单返回数组或模型列表以在提交时执行操作
【发布时间】:2021-05-22 09:42:53
【问题描述】:

我正在做一个学习项目,在该项目中我创建了一个视图,该视图显示通过调用 api 填充的已删除图书列表 (isActive = false)。 该视图在每本书前面都有一个书籍列表+一个复选框,因此在单击我们要设置为活动的书籍并点击保存按钮时,它会将被选中的书籍返回给控制器中的操作。 这是我正在使用的视图:

@model IEnumerable<MvcBooksList.Models.Book>

@{
    ViewData["Title"] = "Delisted Books";
}


@if (Model != null)
{
    @using (Html.BeginForm("DelistedForm", "Book", FormMethod.Post, new { @id = "myForm" }))
    {
        <table class="table">
            <thead>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.BookName)
                    </th>

                    <th>
                        @Html.DisplayNameFor(model => model.Author)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Publisher)
                    </th>
                    <th>
                        Enlist
                    </th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.BookName)
                            @Html.HiddenFor(modelItem => item.BookName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Author)
                            @Html.HiddenFor(modelItem => item.Author)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Publisher)
                            @Html.HiddenFor(modelItem => item.Publisher)

                        </td>
                        <td>
                            @Html.CheckBoxFor(modelItem => item.IsActive)
                        </td>
                    </tr>
                }
            </tbody>
        </table>

        <input type="submit" value="Save" />    <input type = "button" value = "Cancel" onclick = "location.href='@Url.Action("Index", "Home")'" />

        }

    }
    else
    {
    <h3>No Books currently delisted</h3>
}

这是模型:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MvcBooksList.Models
{
    public class Book
    {
        public string BookName { get; set; }
        public string Author { get; set; }
        public string Category { get; set; }
        public string Subcategory { get; set; }
        public string Publisher { get; set; }
        public bool IsActive { get; set; }
        public double? Price { get; set; }
        public int Pages { get; set; }
        public string AddedBy { get; set; }
        public string ModifiedBy { get; set; }
        public DateTime AddedOn { get; set; }
        public DateTime LastModifiedOn { get; set; }
    }
}

这是控制器:


        [HttpPost]
        public async Task<ActionResult> DelistedForm(IEnumerable<Book> fromDelist)
        {
            foreach (var item in fromDelist)
            {
                if (item.IsActive == true)
                //CALL
                {
                    using (HttpClient client = new HttpClient())
                    {
                        client.BaseAddress = baseAddressOfBookApi;
                        var resopnse = await client.GetAsync("Book/EnlistBook?id="+item.BookName.ToString());
                        if (!resopnse.IsSuccessStatusCode)
                        { 
                            return View(null);
                        }
                    }
                }
            }
            return RedirectToAction("Index","Home");
        }

不要介意动作中的代码。

所以当我按下提交按钮时,没有任何东西传递给操作。 fromDelist 集合显示计数为 0。 那么,我做错了什么。 是否有可能我可以返回检查的书名。

BookController ::

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MvcBooksList.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace MvcBooksList.Controllers
{
    public class BookController : Controller
    {
        readonly Uri baseAddressOfBookApi;
        public BookController(IConfiguration configuration)
        {
            baseAddressOfBookApi = new Uri(configuration.GetSection("ApiAddress:BookAPI").Value);
        }


        /* 
         public ActionResult Edit(string name)
         {

             return View(name); //repalce with the name of view
         }

         public ActionResult Delete(string name)
         {
             return View(name);  //repalce with the name of view
         }

         public ActionResult Delist(string name)
         {
             return View(name);   //repalce with the name of view
         }
        */

        public async Task<ActionResult> ViewDelistedBooks()
        {
            List<Book> bookdetails = new List<Book>();
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = baseAddressOfBookApi;
                var response = await client.GetAsync("Book/ViewDelistedBooks");
                if (response.IsSuccessStatusCode)
                {
                    var BookResponse = response.Content.ReadAsStringAsync().Result;
                    bookdetails = JsonConvert.DeserializeObject<List<Book>>(BookResponse);
                }
            }
            return View(bookdetails);
        }

        public ActionResult Cancel()
        {
            return View("~/Views/Home/Index.cshtml");
        }

        [HttpPost]
        public async Task<ActionResult> DelistedForm(IEnumerable<Book> fromDelist)
        {
            foreach (var item in fromDelist)
            {
                if (item.IsActive == true)
                //CALL
                {
                    using (HttpClient client = new HttpClient())
                    {
                        client.BaseAddress = baseAddressOfBookApi;
                        var resopnse = await client.GetAsync("Book/EnlistBook?id="+item.BookName.ToString());
                        if (!resopnse.IsSuccessStatusCode)
                        { 
                            return View(null);
                        }
                    }
                }
            }
            return RedirectToAction("Index","Home");
        }

    }
}

【问题讨论】:

  • 您也可以发布您的控制器吗?
  • 并尝试删除 new { @id = "myForm" } 。你需要它做什么?
  • @Serge ,我刚刚添加了 BookController,是的,抱歉,我将删除它,因为我不使用它...

标签: c# asp.net asp.net-mvc model-view-controller


【解决方案1】:

尝试用for替换foreach

@model List<MvcBooksList.Models.Book>

 @for (int i = 0; i < Model.Count(); i+=1)
{
 ......
             
                       <td>
                            @Html.DisplayFor(model=> model[i].Publisher)
                            @Html.HiddenFor(model => model[i].Publisher)

                        </td>
                        <td>
                            @Html.CheckBoxFor(model => model[i].IsActive)
                        </td>
                    </tr>

.... and so on for all

并替换表头

<th>
                        @Html.DisplayNameFor(model => model[0].BookName)
                    </th>

                    <th>
                        @Html.DisplayNameFor(model => model[0].Author)
                    </th>

【讨论】:

  • 它说:错误 CS0021 无法使用 [] 将索引应用于 'IEnumerable' MvcBooksList 类型的表达式
  • 我更新了我的答案。用 List 替换 IEnumerable。
  • 哇,成功了。感谢您的精彩回答。真的很感激..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多