我的更新功能是更新所有记录,而不只是一个特定记录

时间:2019-07-27 04:47:58

标签: c# model-view-controller

当我更新时,更新将适用于所有建议,而不仅仅是一个建议,我怀疑只有第一个建议会传递给dal。例如,如果有2条建议(“ suggestionid1”和“ suggestionid2”),则当我将建议ID 1从y更新为n时,建议id 2也将从y更新为n。

@model WEB_P02_Team3.Models.Suggestion

@{
    ViewData["Title"] = "AcknowledgeSuggestion";
    Layout = "~/Views/Shared/_StudentLayout.cshtml";
}

<h2>AcknowledgeSuggestion</h2>

<hr />

@if ((ViewData["StudentSuggestion"] as List<Suggestion>).Count > 0)

{
    <tbody>
        <form asp-action="AcknowledgeSuggestion" , asp-controller="Student">
            <fieldset class="FormContent">
                <div class="form-group row">
                    <div>
                        @*<input asp-for="SuggestionID" type="hidden" />
            <input type="hidden" asp-for="SuggestionID" class="form-control" />*@
                        <input type="hidden" asp-for="SuggestionID" />
                        <input type="hidden" asp-for="StudentID" />
                        <input type="hidden" asp-for="LecturerID" />
                        <label asp-for="Status"
                               class="col-sm-3 col-form-label"></label>
                        <div class="col-sm-9 col-md-5">
                            @foreach (var suggestion in ViewData["AcknowledgeSuggestion"]
                                                                     as List<string>)
                            {
                                <label>
                                    <input asp-for="Status" type="radio" value="@suggestion" />
                                    @suggestion
                                </label>
                            }
                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col-sm-9 offset-sm-3">
                            <input type="submit" value="Save"
                                   class="btn btn-primary" />
                        </div>
                    </div>

</form>
    </tbody>
}
else
{
    <span style="color:red"> No suggestion to acknowledge!</span>

}


<a asp-action="Index">Back to List</a>



@model IEnumerable<WEB_P02_Team3.Models.Suggestion>


@{
    ViewData["Title"] = "ViewSuggestion";
    Layout = "~/Views/Shared/_StaffLayout.cshtml";
}

<h2>ViewSuggestion</h2>


<h4>Suggestion</h4>
<hr />

@if (Model.ToList().Count > 0)
{
    <tbody>

        <table style="width:100%; border: 1px solid black;">


            <tr>
                <th>@Html.DisplayNameFor(model => model.SuggestionID)</th>
                <th>@Html.DisplayNameFor(model => model.LecturerID)</th>
                <th>@Html.DisplayNameFor(model => model.StudentID)</th>
                <th>@Html.DisplayNameFor(model => model.Description)</th>
                <th>@Html.DisplayNameFor(model => model.Status)</th>
                <th>@Html.DisplayNameFor(model => model.DateCreated)</th>
            </tr>

            @foreach (var item in Model)
            {
                <tr>
                    <td>@item.SuggestionID.ToString()</td>
                    <td>@item.LecturerID.ToString()</td>
                    <td>@item.StudentID.ToString()</td>
                    <td>@item.Description.ToString()</td>
                    <td>@item.Status.ToString()</td>
                    <td>@item.DateCreated.ToString()</td>

                </tr>
            }

        </table>

        </tbody>


    }
        else
        {
        <span style="color:red"> No record found!</span>
        }


//GET:Student/AchknowledgeSuggestion
        public ActionResult AcknowledgeSuggestion(int? id)
        {
            if ((HttpContext.Session.GetString("Role") == null) ||
               (HttpContext.Session.GetString("Role") != "Student"))
            {
                //Return to listing page, not allowed to edit 
                return RedirectToAction("Index", "Welcome");
            }

            if (id == null) //Query string parameter not provided 
            {

                id = (HttpContext.Session.GetInt32("StudentID"));

            }

            List<Suggestion> studentSuggestionList = suggestionContext.StudentSuggestionList(id.Value);
            //List<Suggestion> suggestionStatusList = new List<Suggestion>();
            List<string> statusSuggestionList = new List<string>();
            statusSuggestionList.Add("Y");
            statusSuggestionList.Add("N");
            //List<Suggestion> suggestionList = suggestionContext.GetAllSuggestion();
           ViewData["AcknowledgeSuggestion"] = statusSuggestionList;
            ViewData["StudentSuggestion"] = studentSuggestionList;
            /*if (studentSuggestionList.Count == 0)
            {
                return RedirectToAction("ViewSuggestion");
            }*/


            Suggestion suggestion = suggestionContext.GetStudentSuggestionDetails(id.Value);
            //suggestion.StudentID = int.Parse(HttpContext.Session.GetString("StudentID"));
            return View(suggestion);
        }

        //POST:Student/AchknowledgeSuggestion
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AcknowledgeSuggestion(Suggestion suggestion)
        {

            if (ModelState.IsValid)
            {
                //Update staff record to database                 
                suggestionContext.Achknowledge(suggestion);
                return RedirectToAction("ViewSuggestion");
            }

            //Input validation fails, return to the view 
            //to display error message             
            return View(suggestion);
        }

public List<Suggestion> StudentSuggestionList(int studentID)
      {

          SqlCommand cmd = new SqlCommand(
          "SELECT * FROM Suggestion WHERE StudentID=@selectedStudentID", conn);
          //Instantiate a DataAdapter object and pass the
          //SqlCommand object created as parameter.
          cmd.Parameters.AddWithValue("@selectedStudentID", studentID);
          SqlDataAdapter da = new SqlDataAdapter(cmd);
          //Create a DataSet object to contain records get from database
          DataSet result = new DataSet();
          //Open a database connection
          conn.Open();
          //Use DataAdapter, which execute the SELECT SQL through its
          //SqlCommand object to fetch data to a table "StudentDetails"
          //in DataSet "result".
          da.Fill(result, "SuggestionDetails");
          //Close the database connection
          conn.Close();
          //Transferring rows of data in DataSet’s table to “Student” objects

          List<Suggestion> StudentSuggestionList = new List<Suggestion>();
          if (result.Tables["SuggestionDetails"].Rows.Count > 0)
          {
              // Fill Skill Set Object with values from the DataSet
              DataTable table = result.Tables["SuggestionDetails"];
              // No errors occurs
              for (int i = 0; i < table.Rows.Count; i++)
              {
                  Suggestion suggestion = new Suggestion();
                  suggestion.StudentID = studentID;

                  if (!DBNull.Value.Equals(table.Rows[i]["SuggestionID"]))
                      suggestion.SuggestionID = Convert.ToInt32(table.Rows[i]["SuggestionID"]);

                  if (!DBNull.Value.Equals(table.Rows[i]["LecturerID"]))
                      suggestion.LecturerID = Convert.ToInt32(table.Rows[i]["LecturerID"]);

                  if (!DBNull.Value.Equals(table.Rows[i]["StudentID"]))
                      suggestion.StudentID = Convert.ToInt32(table.Rows[i]["StudentID"]);

                  if (!DBNull.Value.Equals(table.Rows[i]["Description"]))
                      suggestion.Description = table.Rows[i]["Description"].ToString();

                  if (!DBNull.Value.Equals(table.Rows[i]["Status"]))
                      suggestion.Status = table.Rows[i]["Status"].ToString();

                  if (!DBNull.Value.Equals(table.Rows[i]["DateCreated"]))
                      suggestion.DateCreated = Convert.ToDateTime(table.Rows[i]["DateCreated"]);

                  StudentSuggestionList.Add(suggestion);
              }

          }
          //else
          //{
          //    return null; // There is no existing record found in the database
          //}
          return StudentSuggestionList;

      }

public int Achknowledge(Suggestion suggestion)
       {
           //Instantiate a SqlCommand object, supply it with SQL statement UPDATE
           //and the connection object for connecting to the database.
           SqlCommand cmd = new SqlCommand
           ("UPDATE Suggestion SET Status=@status WHERE StudentID = @selectedStudentID ", conn);
           //Define the parameters used in SQL statement, value for each parameter
           //is retrieved from the respective property of “staff” object.
           cmd.Parameters.AddWithValue("@status", suggestion.Status);
           //cmd.Parameters.AddWithValue("@studentID", suggestion.StudentID);

           cmd.Parameters.AddWithValue("@selectedStudentID", suggestion.StudentID);
           //cmd.Parameters.AddWithValue("@selectedSuggestionID", suggestion.SuggestionID);

           //Open a database connection.
           conn.Open();
           //ExecuteNonQuery is used for UPDATE and DELETE
           int update = cmd.ExecuteNonQuery();
           //Close the database connection.
           conn.Close();
           return update;
       }


public Suggestion GetStudentSuggestionDetails(int studentID)
      {

          SqlCommand cmd = new SqlCommand(
          "SELECT * FROM Suggestion WHERE StudentID=@selectedStudentID", conn);
          //Instantiate a DataAdapter object and pass the
          //SqlCommand object created as parameter.
          cmd.Parameters.AddWithValue("@selectedStudentID", studentID);
          SqlDataAdapter da = new SqlDataAdapter(cmd);
          //Create a DataSet object to contain records get from database
          DataSet result = new DataSet();
          //Open a database connection
          conn.Open();
          //Use DataAdapter, which execute the SELECT SQL through its
          //SqlCommand object to fetch data to a table "StudentDetails"
          //in DataSet "result".
          da.Fill(result, "SuggestionDetails");
          //Close the database connection
          conn.Close();
          //Transferring rows of data in DataSet’s table to “Student” objects
          Suggestion suggestion = new Suggestion();
          if (result.Tables["SuggestionDetails"].Rows.Count > 0)
          {
              suggestion.StudentID = studentID;
              // Fill Skill Set Object with values from the DataSet
              DataTable table = result.Tables["SuggestionDetails"];

              if (!DBNull.Value.Equals(table.Rows[0]["SuggestionID"]))
                  suggestion.SuggestionID = Convert.ToInt32(table.Rows[0]["SuggestionID"]);

              if (!DBNull.Value.Equals(table.Rows[0]["LecturerID"]))
                  suggestion.LecturerID = Convert.ToInt32(table.Rows[0]["LecturerID"]);

              if (!DBNull.Value.Equals(table.Rows[0]["StudentID"]))
                  suggestion.StudentID = Convert.ToInt32(table.Rows[0]["StudentID"]);

              if (!DBNull.Value.Equals(table.Rows[0]["Description"]))
                  suggestion.Description = table.Rows[0]["Description"].ToString();

              if (!DBNull.Value.Equals(table.Rows[0]["Status"]))
                  suggestion.Status = table.Rows[0]["Status"].ToString();

              if (!DBNull.Value.Equals(table.Rows[0]["DateCreated"]))
                  suggestion.DateCreated = Convert.ToDateTime(table.Rows[0]["DateCreated"]);

              return suggestion; // No errors occurs
          }
          else
          {
              return null; // There is no existing record found in the database
          }

      }



using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace WEB_P02_Team3.Models
{
    public class Suggestion
    {
        [Display(Name = "Suggestion ID")]
        public int SuggestionID { get; set; }

        [Display(Name = "Lecturer ID")]
        public int LecturerID { get; set; }

        [Display(Name = "Student ID")]
        public int StudentID { get; set; }

        [StringLength (3000, ErrorMessage ="Maximum 2000 characters" )]
        public string Description { get; set; }

        public string Status { get; set; }

        [DataType(DataType.DateTime)]
        public DateTime DateCreated { get; set; }
    }
} 

0 个答案:

没有答案