控制器和索引视图 ID 和名称匹配。 .net MVC
Controller and index view Id and name match. .net MVC
在我的练习中,我在控制器中有这样的代码
public IActionResult Index(int catId = 0)
{
IEnumerable<Product> products;
if (catId != 0)
{
products = _categoryRepository.GetCategoryByIdWithProducts(catId).Products;
}
else
products = _productRepository.GetAllProducts();
ViewData["SelectList"] = GetCategoriesSelectList();
return View(products);
}
以及视图中的此类代码
<div class="form-group">
<label for="categoryId">Filter by category</label>
<select id="catId" name="catId" asp-items="@(ViewData["SelectList"] as SelectList)" class="form-control">
<option value="">-- all categories --</option>
</select>
</div>
<button type="submit" class="btn btn-secondary ml-1">Submit</button>
而且我真的不明白这个标签 id="catId" name="catId" 在视图和控制器 Index(int catId = 0) 中是如何相互匹配的。
如果我删除 id="catId" 提交按钮工作,如果我删除 name="catId" 它不。
mvc 外观或参数和名称是否匹配,或者它是如何工作的?
亲切的问候,伊利亚
does the mvc looks or the argument and name match or how does it works?
是的,name 属性用于引用 JavaScript 中的元素,或者在提交表单后引用表单数据。只有具有 name 属性的表单元素才会在提交表单时传递其值。您可以使用 f12 网络选项进行检查。
此外,mvc中的modelbinding也是基于name而不是id。
- id 用于通过文档对象模型(通过 JavaScript 或使用 CSS 设置样式)来标识 HTML 元素。 id 应该在页面内是唯一的。
- 名称对应于表单元素并标识回传到服务器的内容。
在我的练习中,我在控制器中有这样的代码
public IActionResult Index(int catId = 0)
{
IEnumerable<Product> products;
if (catId != 0)
{
products = _categoryRepository.GetCategoryByIdWithProducts(catId).Products;
}
else
products = _productRepository.GetAllProducts();
ViewData["SelectList"] = GetCategoriesSelectList();
return View(products);
}
以及视图中的此类代码
<div class="form-group">
<label for="categoryId">Filter by category</label>
<select id="catId" name="catId" asp-items="@(ViewData["SelectList"] as SelectList)" class="form-control">
<option value="">-- all categories --</option>
</select>
</div>
<button type="submit" class="btn btn-secondary ml-1">Submit</button>
而且我真的不明白这个标签 id="catId" name="catId" 在视图和控制器 Index(int catId = 0) 中是如何相互匹配的。
如果我删除 id="catId" 提交按钮工作,如果我删除 name="catId" 它不。
mvc 外观或参数和名称是否匹配,或者它是如何工作的?
亲切的问候,伊利亚
does the mvc looks or the argument and name match or how does it works?
是的,name 属性用于引用 JavaScript 中的元素,或者在提交表单后引用表单数据。只有具有 name 属性的表单元素才会在提交表单时传递其值。您可以使用 f12 网络选项进行检查。
此外,mvc中的modelbinding也是基于name而不是id。
- id 用于通过文档对象模型(通过 JavaScript 或使用 CSS 设置样式)来标识 HTML 元素。 id 应该在页面内是唯一的。
- 名称对应于表单元素并标识回传到服务器的内容。