3

ユーザーがコメントを入力し、[更新] をクリックして 1 行のデータを更新できるテキスト ボックスのあるテーブルを持つ 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>

<% }%>

行で更新をクリックすると、このコントローラーが呼び出されます。配列には、その行の個々のテキストボックス/テキスト領域のコレクションからの値が含まれています。

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();
            }
        }
}
4

1 に答える 1

0

モデルをリストにバインドする場合、生成された ID を一意に保つために、一意の識別子を各行に追加する必要があります。

foreach ではなく for ループを使用した例を次に示します (かみそりではなく、古い学校の ASP ビューで記述されています)。

<%@ 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

于 2013-08-30T14:29:40.390 に答える