【问题标题】:What is wrong in my code that my dropdown list isn't working我的代码有什么问题,我的下拉列表不起作用
【发布时间】:2021-05-17 13:28:12
【问题描述】:

这是我的索引操作, 我把所有产品都放在我的视野里

public async Task<IActionResult> Index()
{
    return View(await _productRepo.GetAllAsync());
}

这是我的创建动作, 我选择了所有要查看的类别 ID 和名称。类别

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,SKU,Description,Price,OldPrice,Status,IsMenuItem,Count,CategoryId")] Product productModel)
{
    ViewBag.Categories = new SelectList(await _categoryrepo.GetAllAsync() , "Id" , "Name");

    if (ModelState.IsValid)
    {
        await _productRepo.CreateAsync(productModel);
        return RedirectToAction(nameof(Index));
    }

    return View(productModel);
}

这是我的看法

@model OnlineShopArmenia.Models.Product

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Product</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="SKU" class="control-label"></label>
                <input asp-for="SKU" class="form-control" />
                <span asp-validation-for="SKU" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Description" class="control-label"></label>
                <input asp-for="Description" class="form-control" />
                <span asp-validation-for="Description" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Price" class="control-label"></label>
                <input asp-for="Price" class="form-control" />
                <span asp-validation-for="Price" class="text-danger"></span>
            </div>
            <div class="form-group form-check">
                <label class="form-check-label">
                    <input class="form-check-input" asp-for="Status" /> @Html.DisplayNameFor(model => model.Status)
                </label>
            </div>
            <div class="form-group form-check">
                <label class="form-check-label">
                    <input class="form-check-input" asp-for="IsMenuItem" /> @Html.DisplayNameFor(model => model.IsMenuItem)
                </label>
            </div>
            <div class="form-group">
                <label asp-for="Count" class="control-label"></label>
                <input asp-for="Count" class="form-control" />
                <span asp-validation-for="Count" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label>Categories :</label>
                <select name="Id" asp-for="Id" class="formcontrol" asp-items="ViewBag.Categories">
                    <option value="@ViewBag.Categories"></option>
                </select>
                <span asp-validation-for="Id" class="text-danger"></span>
            </div>

            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

这是产品模型

public class Product
    {
        [Key]
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        public string SKU { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public bool Status { get; set; }
        public bool IsMenuItem { get; set; }
        public int Count { get; set; }
        public int? CategoryId { get; set; }
        public Category Category { get; set; }
    }

这是类别模型

public class Category
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
    }

This is the result

我想在下拉列表中查看类别,我该怎么做? 我认为我们必须更改&lt;select&gt;&lt;option&gt;标签中的属性, 请帮我解决它

【问题讨论】:

  • 您需要删除&lt;option value="@ViewBag.Categories"&gt;&lt;/option&gt;并将asp-items="ViewBag.Categories"更改为asp-items="@ViewBag.Categories"
  • 没有帮助
  • 你的控制器中还有其他CreateAction方法吗?
  • 是--------- public IActionResult Create() { return View(); }
  • 需要在Create()return View();之前添加ViewBag.Categories = new SelectList(await _categoryrepo.GetAllAsync() , "Id" , "Name");代码

标签: c# html asp.net asp.net-mvc razor


【解决方案1】:
  1. 您使用了错误的操作方法。对于创建操作,您的控制器应该有两个操作方法 - GET 方法和 POST 方法。您现在使用的那个(标有[HttpPost])用于从您的视图接收数据,一旦您尝试保存它们。要将数据传递给视图(在创建视图时),请使用标记有[HttpGet] 属性(或者根本没有标记任何属性)的操作方法。遵循GET 方法应该足以创建您的视图 -
[HttpGet]  // this attribute is optional
public IActionResult Create()
{
    ViewBag.Categories = new SelectList(await _categoryrepo.GetAllAsync() , "Id" , "Name");
    return View();
}
  1. 您将select标记错误,它应该代表外键属性CategoryId,而不是产品的Id-
<select asp-for="CategoryId" class ="form-control" asp-items="ViewBag.Categories"></select>

你不需要option 标签,除非你想要像Please select a Category 这样的显示值 -

<select asp-for="CategoryId" class ="form-control" asp-items="ViewBag.Categories">
    <option value="">Please choose user category:</option>
</select>

编辑:
我不确定您使用的是什么版本的 ASP.NET MVC 或 ASP.NET Core MVC,但上面的 razor 语法适用于 .NET 5

【讨论】:

  • 不应该是asp-items="@ViewBag.Categories"
  • @ChetanRanpariya 不确定以前的版本,我从未使用过 ASP.NET MVC、Core 或非 Core。但这适用于.Net 5。我将为此添加一个编辑。
【解决方案2】:

您应该有 2 个操作 - 创建或编辑视图和保存数据。

您创建视图的操作应如下所示:

[HttpGet]  // this attribute is optional
public async Task<IActionResult> Create()
{
  
    return  await Edit(0);
}
[HttpGet("{id?}")]
public async Task<IActionResult> Edit(int id)
{
      ProductModel model=null;
if id=0 model=new Product();
else model= await _productRepo.GetAsync(id);
 ViewBag.Categories = new SelectList(await _categoryrepo.GetAllAsync() 
, "Id" , "Name");

    return View(model);
}

并修正您的选择:

 <select name="categoryId" asp-for="CategoryId" class="formcontrol" asp-items="@ViewBag.Categories">
 </select>

【讨论】:

  • (1)。 [HttpGet] 方法不需要 [ValidateAntiForgeryToken] 属性,(2)。您不需要 id 参数并获取现有产品,因为它是一个创建操作,(3)select 标签应该代表 CategoryId 属性,而不是 Id
  • @atiyar- 感谢 CategoryId ,我永远不会习惯某些人可以在一行代码中犯这么多错误。所以我没有检查一切。关于 ID - 我通常使用相同的操作来创建新的和编辑现有的。只需检查 id 来决定是创建新的还是编辑。
猜你喜欢
  • 1970-01-01
  • 2018-01-26
  • 2019-11-06
  • 2013-11-12
  • 2014-09-06
  • 2016-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多