내 응용 프로그램에서 MVC를 사용하여 데이터를 삭제하려고합니다. 먼저 데이터베이스에서 레이블로 레코드를 가져옵니다. 그런 다음 삭제하려고합니다. 이것은 당신이 StudentData 내가 속성을 정의하는 클래스를 참조로 내 컨트롤러MVC 4를 사용하여 데이터베이스에서 레코드를 삭제할 수 없습니다.
public ActionResult Delete(string id)
{
DBData dbData = new DBData();
StudentData sd = new StudentData();
DataSet ds;
ds = dbData.SelectUserById(id);
sd.SID = Convert.ToInt32(ds.Tables[0].Rows[0]["sid"].ToString());
sd.StudentName = ds.Tables[0].Rows[0]["studentname"].ToString();
sd.ContactNo = ds.Tables[0].Rows[0]["contactno"].ToString();
sd.EmailId = ds.Tables[0].Rows[0]["emailid"].ToString();
return View(sd);
}
[HttpPost]
public ActionResult Delete(StudentData sd)
{
if (ModelState.IsValid)
{
DBData db = new DBData();
db.DeleteRecord(sd);
return RedirectToAction("SelectAllStudent", "Student");
}
else
{
ModelState.AddModelError("", "Error while Deleting data");
return View();
}
}
의 코드가 여기 내 모델
public void DeleteRecord(StudentData sd)
{
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("delete from studentinfo where [email protected]", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@sid", sd.SID);
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch
{
}
finally
{
con.Close();
}
}
입니다
아래 내가 쓰고 있어요 코드입니다. 내 기록을 매번를 삭제하려고 할 때
지금 여기 지금 내보기
@model CrudMVC.Models.StudentData
@{
ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>StudentData</legend>
<div class="display-label">
@Html.DisplayNameFor(model => model.SID)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.SID)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.StudentName)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.StudentName)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.EmailId)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.EmailId)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.ContactNo)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.ContactNo)
</div>
</fieldset>
@using (Html.BeginForm()) {
<p>
<input type="submit" value="Delete" /> |
@Html.ActionLink("Back to List", "SelectAllStudent")
</p>
}
이다 아닌 하나의 기록은 .I이 중단 점을 추가하고 값을 확인 삭제되었습니다. 그러나 HttpPost 함수 StudentData sd에는 단일 값이 없습니다. 그것들은 null을 보여줍니다. 왜 이러한 속성들은 비어 있습니다. 전문가들은 나를
'
숨겨진 필드 트릭 작업. 숨겨진 필드에 sid를 추가했습니다. 그러나 나는 그것이 왜 일어나는 지 이해하지 못한다. @Nilesh –
@Stephen의 답을 확인하십시오. 'DisplayFor'는 입력 요소가 아닌 태그를 생성합니다. 양식을 제출하면 입력 필드 만 현재 값으로 전기됩니다. 그래서 당신의 경우에는'StudentModel'을 당신의 액션에 대한 입력으로 기대하고 있습니다. 을 렌더링 할 때 결코 작동하지 않을 것입니다. 또한 내가 레코드를 삭제할 때주의해야 할 것은 레코드의 ID 만 삭제되므로'Delete (StudentModel student)'메소드를'Delete (int studentId)'로 변경하면된다. – Nilesh