c# - MVC2 c# 表格中的多种形式。一种表单在回发时覆盖其他表单元素

标签 c# asp.net-mvc forms

我有一个 ASP.Net MVC2 应用程序,它有一个带文本框的表格,用户可以在其中输入评论并单击更新以更新单行数据。表的每一行都是通过基于日期调用数据库生成的 for each 循环,由用户输入,并包装在名称为 commentaryForm 的表单中 - 就像这样

<% foreach (var item in Model)
       using (Html.BeginForm("Commentary", "Home", FormMethod.Post, new { name = "commentaryForm", id = "commentaryForm" }))
       { %>
    <tr>
    <td><%= Html.TextBox("comDate", item.aReportingDate.ToString().Substring(0, 10), new { @readonly = true, @class = "readOnlyTBox" })%></td>
<td><%= Html.Encode(item.BPM)%></td>
<td><%= Html.Encode(item.criticality)%></td>
<td><%= Html.Encode(item.team)%></td>
<td><%= Html.Encode(Convert.ToInt32(item.newIn))%></td>
<td><%= Html.Encode(Convert.ToInt32(item.outsideSLA))%></td>
<td><%= Html.TextArea("why", item.commentaryWhy, new { @class = "commentaryInput" })%></td>
<td><%= Html.TextArea("what", item.commentaryWhat, new { @class = "commentaryInput" })%></td>
<td><%= Html.TextBox("when", item.commentaryWhen, new { @class = "when" })%></td>
<td id="resultsTd"><input type="submit" class="submitButton noMargin" value="Update" /></td>
<td class=""><%= Html.Encode(item.commentaryId)%> <%= Html.TextBox("id", item.commentaryId, new { @class = "when", type = "", value = item.commentaryId })%></td>

</tr>

<% }%>

单击一行中的更新会调用此 Controller ,其中数组包含来自该行中各个文本框/文本区域集合的值。

public ActionResult Commentary(string[] why, string[] what, DateTime[] when, int[] id)
    {

        var reportingDate = new DateTime();
        reportingDate = Convert.ToDateTime(Request.Form["comDate"]);
        if (reportingDate.ToString().Substring(0, 10).Equals(@"01/01/0001"))
        {
            DateTime latestDay = DateTime.Now.AddDays(-1);
            reportingDate = latestDay;
            ViewData["start"] = latestDay.ToString().Substring(0, 10);
        }
        else
            ViewData["start"] = reportingDate.ToString().Substring(0, 10);


        var model = new List<commentaryVModel>();

        if (why != null && what != null && when != null && id != null)
            {
            DataLayer.Updatedata(id, why, what, when);
            }
        model = DataLayer.viewCommentary(model, reportingDate);
        return View(model);

    }

DataLayer.UpdatedataDataLayer.viewCommentary(model, reportingDate) 似乎在步进时工作正常,并且值符合预期。

问题是当您点击更新后页面重新加载时,所有表格行中的值都已被您更新的行中的值替换!仅在用户看到的 DOM 中,而不是在数据库中!诡异的!

有人可以帮忙吗?谢谢!我已经在下面发布了数据库方法的代码,但我还不能发布屏幕截图,因为这是我的第一个问题。

public static List<commentaryVModel> viewCommentary(List<commentaryVModel> model, DateTime reportingDate)
{
        SqlConnection con = DataLayer.getConnection();
        SqlDataReader reader = null;
        string commandString = DataLayer.Commentary();
        SqlCommand command = new SqlCommand(commandString, con);
        command.CommandType = CommandType.StoredProcedure;
        // add parameters
        command.Parameters.AddWithValue("@reportingDate", reportingDate);

        try
        {
                // execute a reader with the command
                reader = command.ExecuteReader();
                {
                    // loop in the result and fill the list
                    while (reader.Read())
                    {
                        // add items in the list
                        model.Add(new commentaryVModel()
                        {
                            BPM = reader["BPM"] as string,
                            aReportingDate = (DateTime)reader["date"],
                            team = reader["Team"] as string,
                            criticality = reader["Criticality"] as string,
                            newIn = (decimal)reader["NewIn"],
                            outsideSLA = (decimal)reader[@"OutsideSLA"],
                            commentaryId = (int)reader[@"Id"],
                            commentaryWhy = reader[@"CommentaryWhy"] as string,
                            commentaryWhat = reader[@"CommentaryWhat"] as string,
                            commentaryWhen = reader[@"CommentaryWhen"] as string
                        });
                    }
                }
        }
        catch
        { }
        finally
        {
                // 3. close the reader
                if (reader != null)
                {
                    reader.Close();
                }

                // close the connection
                if (con != null)
                {
                    con.Close();
                }
        }

public static void Updatedata(int[] id, string[] why, string[] what, DateTime[] when)
{
        SqlConnection con = DataLayer.getConnection();
        try
        {
            string fullString = null;
            // prepare command string
            for (int i = 0; i < id.Length; i++)

            {
                string updateString = @"
            UPDATE   tCommentary
            SET      CommentaryWhy = '" + why[i] + "'" +
                    ",CommentaryWhat = '" + what[i] + "'" +
                    ",CommentaryWhen = '" + when[i] + "'" +
            "WHERE    rowId = " +  id[i] + " ";
            fullString = fullString + " " + updateString;
            }

            // 1. Instantiate a new command with a query and connection
            SqlCommand cmd = new SqlCommand(fullString, con);
            // 2. Call ExecuteNonQuery to send command
            cmd.ExecuteNonQuery();

        }
        catch
        { }
        finally
        {
            // Close the connection
            if (con != null)
            {
                con.Close();
            }
        }
}

最佳答案

当模型绑定(bind)到列表时,您需要将唯一标识符附加到每一行,以保持生成的 ID 的唯一性。

这是一个使用 for 循环而不是 foreach 的例子(它是用老派的 asp View 编写的,而不是 razor)

<%@ Page Inherits="ViewPage<IList<Book>>" %>

    <% for (int i = 0; i < 3; i++) { %>

      <%: Html.TextBoxFor(m => m[i].Title) %>
      <%: Html.TextBoxFor(m => m[i].Author) %>
      <%: Html.TextBoxFor(m => m[i].DatePublished) %> 

    <% } %>

这将生成具有唯一 ID 的文本框,允许您以单个表单回发多个项目。您显然正在尝试制作多个表单,这仍然可以工作,只需为每个表单提供一个唯一的 ID。

看看 phil haacks 关于这个主题的经典文章。我知道它针对的是早期版本的 mvc,但原理还是一样的。

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

关于c# - MVC2 c# 表格中的多种形式。一种表单在回发时覆盖其他表单元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16968237/

相关文章:

javascript - 使用 Asp.Net MVC 和 KnockoutJS 处理日期

asp.net-mvc - 我需要在 MVC 5 中获取当前用户名

c# - 使用模拟 Controller 上下文来测试 Controller

PHP session 变量 - 传递页面

c# - ASP.NET MVC5 在 ListView 中获取所有注册的 AspNetUsers

c# - 该文件不是有效的 VSIX 包

php - while循环无限重复

javascript - React 初学者在将 Material-UI 示例应用到 React 项目时遇到问题。 State 与 Hooks 的工作方式不同

c# - 多部分短信解码

c# - 原始并发读写的线程安全