【问题标题】:How to get the values from the form submitted when they're not declared on the action method?未在操作方法上声明时如何从提交的表单中获取值?
【发布时间】:2020-10-27 21:39:37
【问题描述】:

有没有办法从 HTTP Post 请求期间提交的表单中查找值,即使它们没有在视图模型上声明或作为操作方法的参数?当然是在 ASP.NET CORE MVC 上。

我会给你更多关于我正在尝试做的事情的背景信息。

我正在尝试将产品插入数据库。查看它的类和依赖项,然后查看产品视图模型,最后查看它。
小结:

  • 每个产品都有很多子类别

  • 每个子类别都有很多产品

  • 因此 ProductSubcategory 类。

  • 每个产品都有一个类别。


Product.cs

public class Product
    {
        public int ProductId { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public Category Category { get; set; }
        public IEnumerable<ProductSubCategory> SubCategories { get; set; } 
}

ProductSubCategory.cs

public class ProductSubCategory
{
    public int ProductId { get; set; }
    public Product Product { get; set; }
    public int SubCategoryId { get; set; }
    public SubCategory SubCategory { get; set; }
}

SubCategory.cs

public class SubCategory
{
    public int SubCategoryId { get; set; }
    public string Name { get; set; }
    public Category Category { get; set; }
    public IEnumerable<ProductSubCategory> ProductSubCategories { get; set; }
}

Category.cs

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public IEnumerable<Product> Products { get; set; }
}


ProductViewModel.cs

public class ProductViewModel
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public double? Price { get; set; }
    public SelectList Categories { get; set; }
    public int? CategoryId { get; set; }
}


Insert.cshtml

  • 要获得一个或多个 SubCategories,您必须先从选择中选择一个类别。
@model ProductViewModel
<form enctype="multipart/form-data" method="post" asp-controller="Product" asp-action="Add">
            <div class="form-group">
                <label asp-for="Name"></label>
                <input type="text" class="form-control" asp-for="Name" placeholder="Cereal, Ice cream, Tuna, etc...">
            </div>
            <div class="form-group">
                <label asp-for="Price"></label>
                <input type="text" class="form-control" asp-for="Price" placeholder="5 , 23.5 , 50.231">
            </div>
            <div class="form-group">
                <label asp-for="Categories"></label>
                <select asp-for="CategoryId" asp-items="@Model.Categories" class="custom-select">
                    <option value="">Please select one</option>
                </select>
            </div>
            <label>Subcategories</label>
            @* Here we'll put the subcategories ( <input type="checkbox"/> ) according to the category selected,
             each subcategory will be represented by a checkbox *@
            <button class="btn btn-primary">Create</button>
        </form>

好的,现在问题来了,我不知道如何映射/查找/搜索用户在视图上标记的子类别 (&lt;input type="checkbox"/&gt;),因为它们没有直接在视图和视图模型上声明。为什么?因为不可能,因为子类别的数量取决于用户选择的类别,所以如果他选择糖果类别,那么下面会显示焦糖、巧克力和软糖等子类别,如果他选择肉类类别,然后是猪肉、鸡肉和牛肉等子类别,以此类推……每个类别都由&lt;input type="checkbox"/&gt; 表示。
我必须知道选择了哪些,因为我必须在控制器上进行某种算法才能创建子类别实例并将它们分配给产品实例,这样我才能最终插入它。

【问题讨论】:

  • 听起来你想要一个随着用户选择选项而改变的动态表单。您可以使用 JavaScript 和多个 AJAX 调用来获取子选项(参见此处以获取示例 stackoverflow.com/questions/18351921/…)。最终提交将需要所有相关的输入元素,或者您可以构建一个您将发布的 json 对象。
  • @Jasen 是的,它是一种动态形式,我知道如何使其动态化。这不是我要的。 Controller - Post Action Method 如何知道选择了哪些子类别?因为它可以是 4 或 5 或 6 ,谁知道呢。我需要确定,否则我无法创建子类别,然后插入 ProductSubCategory。

标签: c# asp.net-core asp.net-core-mvc


【解决方案1】:

我根据你的代码和描述做了一个demo,你可以参考下面的代码:

视图模型:

public class ProductViewModel
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public double? Price { get; set; }
    public List<SelectListItem> Categories { get; set; }
    public int? CategoryId { get; set; }
}

查看:

@model ProductViewModel

<form enctype="multipart/form-data" method="post" asp-controller="Product" asp-action="Create">
    <div class="form-group">
        <label asp-for="Name"></label>
        <input type="text" class="form-control" asp-for="Name" placeholder="Cereal, Ice cream, Tuna, etc...">
    </div>
    <div class="form-group">
        <label asp-for="Price"></label>
        <input type="text" class="form-control" asp-for="Price" placeholder="5 , 23.5 , 50.231">
    </div>
    <div class="form-group">
        <label asp-for="Categories"></label>
        <select asp-for="CategoryId" asp-items="@Model.Categories" class="custom-select">
            <option value="">Please select one</option>
        </select>
    </div>
    <label>Subcategories</label>
    <div id="subcategories"></div>
    <button class="btn btn-primary">Create</button>

</form>

@section scripts{ 
<script>
    $("#CategoryId").on("change", function () {
        var categoryId = $(this).val();
        $.ajax({
            method: 'get',
            url: '/Product/GetSubCategories?categoryId=' + categoryId,
            success: function (result) {
                var htmlString = "";
                for (var i = 0; i < result.length; i++) {
                    htmlString += "<input type='checkbox' name='subCategories' value = '" + result[i].subCategoryId + "' />";
                    htmlString += "<label>"+result[i].name+"</label>"
                }
                $("#subcategories").append(htmlString);
            }

        })

    })
</script>
}

控制器:

public IActionResult Create()
{
    var categories = _db.Categories.ToList();
    var viewModel = new ProductViewModel();
    var categorylist = new List<SelectListItem>();
    foreach (var category in categories)
    {

        categorylist.Add(
            new SelectListItem()
            {
                Text = category.Name,
                Value = category.CategoryId.ToString()
            });
    }
    viewModel.Categories = categorylist;
    return View(viewModel);
}

public List<SubCategory> GetSubCategories(int categoryId)
{
    var subcategories = _db.SubCategories.Where(s => s.Category.CategoryId == categoryId).ToList();
    return subcategories;
}

[HttpPost]
public IActionResult Create(Product product, List<int> subCategories)
{
    //do stuff     
    return View();
}

结果:

【讨论】:

  • 哥们,你是最棒的,你给的比我要求的多,多亏了我消除了所有的疑虑。
  • asp.net core mvc 是否有某种标签助手来简化 AJAX?这是因为我必须学习 AJAX,所以如果有办法让我的代码更干净,那就太好了。
  • 如果我有数千个子类别或更多子类别怎么办。我们不能做那么多复选框。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
  • 2019-11-04
  • 2019-08-25
  • 1970-01-01
  • 2018-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多