gpt4 book ai didi

c# - 向 MVCcontrib 网格上的每一行添加复选框

转载 作者:可可西里 更新时间:2023-11-01 09:06:50 26 4
gpt4 key购买 nike

如何向 MVCcontrib 网格的每一行添加一个复选框。然后在发布表格时找出选择了哪些记录?我在搜索时找不到太多。谢谢

最佳答案

以下是您可以如何继续:

型号:

public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsInStock { get; set; }
}

Controller :

public class HomeController : Controller
{
public ActionResult Index()
{
var products = new[]
{
new Product { Id = 1, Name = "product 1", IsInStock = false },
new Product { Id = 2, Name = "product 2", IsInStock = true },
new Product { Id = 3, Name = "product 3", IsInStock = false },
new Product { Id = 4, Name = "product 4", IsInStock = true },
};
return View(products);
}

[HttpPost]
public ActionResult Index(int[] isInStock)
{
// The isInStock array will contain the ids of selected products
// TODO: Process selected products
return RedirectToAction("Index");
}
}

查看:

<% using (Html.BeginForm()) { %>
<%= Html.Grid<Product>(Model)
.Columns(column => {
column.For(x => x.Id);
column.For(x => x.Name);
column.For(x => x.IsInStock)
.Partial("~/Views/Home/IsInStock.ascx");
})
%>
<input type="submit" value="OK" />
<% } %>

部分:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyNamespace.Models.Product>" %>
<!--
TODO: Handle the checked="checked" attribute based on the IsInStock
model property. Ideally write a helper method for this
-->
<td><input type="checkbox" name="isInStock" value="<%= Model.Id %>" /></td>

最后,这里有一个可以用来生成此复选框的辅助方法:

using System.Web.Mvc;
using Microsoft.Web.Mvc;

public static class HtmlExtensions
{
public static MvcHtmlString EditorForIsInStock(this HtmlHelper<Product> htmlHelper)
{
var tagBuilder = new TagBuilder("input");
tagBuilder.MergeAttribute("type", "checkbox");
tagBuilder.MergeAttribute("name", htmlHelper.NameFor(x => x.IsInStock).ToHtmlString());
if (htmlHelper.ViewData.Model.IsInStock)
{
tagBuilder.MergeAttribute("checked", "checked");
}
return MvcHtmlString.Create(tagBuilder.ToString());
}
}

这简化了部分:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyNamespace.Models.Product>" %>
<td><%: Html.EditorForIsInStock() %></td>

关于c# - 向 MVCcontrib 网格上的每一行添加复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3074271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com