2

这是我第一次发帖!:)

我必须将我的模型数组从我的控制器类返回到视图页面。我想将数据放入文本框中并为每个文本框生成动态 id,以通过 JavaScript 进一步使用数据(这就是我寻找动态 id 的原因)。

模型

public partial class BhBuyerChart
{
    public string Date { get; set; }
    public string Quantity { get; set; }

    public BhBuyerChart(string n, string d)
    {
        Date = n;
        Quantity = d;
    }
}

控制器

public ActionResult test()
{
     BhBuyerChart[] model = new BhBuyerChart[7];

     DataTable dt = (DataTable)ExecuteDB(ERPTask.AG_GetAllShipmentRecord, CurrentUserId);
     List<BhBuyerChart> ItemList = null;
     ItemList = new List<BhBuyerChart>();
     int i = 0;
     foreach (DataRow dr in dt.Rows)
     {
         model[i] = new BhBuyerChart(dr["Shipmentdate"].ToString(), dr["ShipmentQuantity"].ToString());
         i++;
     };

     return View(model);
}

看法

第一次尝试

<div>
    <% for (int i=0; i<2; i++) {%>
    <%: Html.TextBoxFor(m => m[i].Quantity, new { id = "Quantity"})%>    <%--value can assign from model but dnt know how to assing dynamic id --%>

    <input type="text" value="<%= i %>" id="text<%=i %>"/>                 <%--dynamic id can be assinged dnt knw how to assing model value here in textbox --%>
    <% } %>
</div>

第二次尝试

<div>
<% int i = 0; %>
<% foreach (ERP.Domain.Model.BhBuyerChart user in Model) {  %>
      <% i++; %>
      <input type="text"; id="textbox<% i %>" ; value="<% user.Quantity %>" />   
 <% } %>
 </div>

非常感谢大家的关注和帮助,期待您的回复!

4

3 回答 3

0

您需要 Steven Sanderson 制作的出色扩展,称为BeginCollectionItem. 对于模型中的每一行,每个输入都将继承一个唯一的 guid,您可以将其重用于验证或其他内容。

有关如何逐步使用扩展的更多信息,请参阅 Steven Sanderson 博客上的文章:编辑可变长度列表,ASP.NET MVC 2-style

这篇文章是为 MVC2 编写的,但它也适用于 MVC3。它应该在 MVC4 中工作,但我还没有测试过。

看法

<% foreach (var item in Model) {
    <% using(Html.BeginCollectionItem("bhBuyerItem")) { %>
        <%= Html.TextBoxFor(m => m.Quantity) %>
        <%= Html.TextBoxFor(m => m.Date) %>
    <% } %>
<% } %>

扩展方法

public static class HtmlPrefixScopeExtensions
{
    private const string idsToReuseKey = "__htmlPrefixScopeExtensions_IdsToReuse_";

    public static IDisposable BeginCollectionItem(this HtmlHelper html, string collectionName)
    {
        var idsToReuse = GetIdsToReuse(html.ViewContext.HttpContext, collectionName);
        string itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : Guid.NewGuid().ToString();

        // autocomplete="off" is needed to work around a very annoying Chrome behaviour whereby it reuses old values after the user clicks "Back", which causes the xyz.index and xyz[...] values to get out of sync.
        html.ViewContext.Writer.WriteLine(string.Format("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, html.Encode(itemIndex)));

        return BeginHtmlFieldPrefixScope(html, string.Format("{0}[{1}]", collectionName, itemIndex));
    }

    public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix)
    {
        return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
    }

    private static Queue<string> GetIdsToReuse(HttpContextBase httpContext, string collectionName)
    {
        // We need to use the same sequence of IDs following a server-side validation failure,  
        // otherwise the framework won't render the validation error messages next to each item.
        string key = idsToReuseKey + collectionName;
        var queue = (Queue<string>)httpContext.Items[key];
        if (queue == null) {
            httpContext.Items[key] = queue = new Queue<string>();
            var previouslyUsedIds = httpContext.Request[collectionName + ".index"];
            if (!string.IsNullOrEmpty(previouslyUsedIds))
                foreach (string previouslyUsedId in previouslyUsedIds.Split(','))
                    queue.Enqueue(previouslyUsedId);
        }
        return queue;
    }

    private class HtmlFieldPrefixScope : IDisposable
    {
        private readonly TemplateInfo templateInfo;
        private readonly string previousHtmlFieldPrefix;

        public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix)
        {
            this.templateInfo = templateInfo;

            previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
            templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
        }

        public void Dispose()
        {
            templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix;
        }
    }
}
于 2012-08-30T15:46:23.930 回答
0

经过几次尝试,我想我能够做到这一点

<%for (int i = 0; i <= 1; i++)%>
<%  {  %>
  <div style="width:100%; float:left">
     <%: Html.TextBoxFor(m => m[i].Date, new { id= i+500 })%>
     <%: Html.TextBoxFor(m => m[i].Quantity, new { id = i })%>

     <%: Html.TextBoxFor(m => m[i].Quantity) %>

   </div>         
<script type="text/javascript">
    var val = [[], []];
    for (k = 0; k <= 1; k++) {
        val[k][0] = document.getElementById(k+300).value;
        val[k][1] = parseInt(document.getElementById(k).value);

    }
</script>

这将从模型数组中获取动态数据并为每个文本框创建动态 id 并使用动态 id 将它们分配给变量

于 2012-08-30T16:19:59.343 回答
0

我认为这应该为你做。实际上,您要做的是在控制器内部构建一个新方法,以便您可以使用更新后的值 POST 回控制器。此外,您不希望Quantity字段具有不同的名称,因为它们不会绑定 - 因此您构建的每个字段都会在生成 HTML 时Quantityname and id属性中说明。

如果我误解了您的需求,请发表评论。

控制器

public ActionResult test()
{
     BhBuyerChart[] model = new BhBuyerChart[7];

     DataTable dt = (DataTable)ExecuteDB(ERPTask.AG_GetAllShipmentRecord, CurrentUserId);
     List<BhBuyerChart> ItemList = null;
     ItemList = new List<BhBuyerChart>();
     int i = 0;
     foreach (DataRow dr in dt.Rows)
     {
         model[i] = new BhBuyerChart(dr["Shipmentdate"].ToString(), dr["ShipmentQuantity"].ToString());
         i++;
     };

     return View(model);
}

[HttpPost]
public ActionResult test(ICollection<BhBuyerChart> charts)
{
    // This allows you to POST to the controller with the modified values

    // Note that based on what you're collecting client side the charts
    // will ONLY contain the Quantity value, but they will all have one.
    // If you need the date you can either show a text box for that or
    // even place the date inside a hidden field.
}

看法

<form method="post" action="/{controllername}/test">
...
<div>
    <% for (int i=0; i<2; i++) {%>
        <!-- This line will both bind the value and allow you to POST -->
        <!-- this form back to the controller with the new values -->

        <!-- NOTE: each control is actually going to be named the same -->
        <!-- but when it's posted will post in order to the collection -->
        <%: Html.TextBoxFor(m => m[i].Quantity) %>

        <!-- You may or may not want this here so that you can get the -->
        <!-- value of the date back to the server during a POST -->
        <%: Html.HiddenFor(m => m[i].Date) %>
    <% } %>
</div>
...
</form>

JavaScript

现在在 JavaScript 中,您可以使用 jQuery 简单地获取所有Quantity像这样命名的元素的列表,并从该数组中使用它们。

// with this ([0].Quantity) being the template
// we'll use a simple wildcard selector to find
// all of them that end with Quantity.

var elems = $("[name$=Quantity]")

// now you have a list of the elements that you
// can use to populate the other array with -
// getting the value with a statement like...

var val = elems[0].val();
于 2012-08-30T11:01:09.767 回答