1

I am trying to delete data using MVC in my application. For this first I am fetching the records from the database into the labels. Then I am trying to delete this. The code which I am writing is below

This is the code of my Controller

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

Here is my model

 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 sid=@sid", con);
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@sid", sd.SID);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
        }

as you see StudentData is a class in which I define properties.

Now here is my View

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

Now when I am trying to delete my record everytime,not a single record was deleted .I add breakpoint and check the values. But In HttpPost function StudentData sd had not any single value. Its show me null.Why these properties are empty I dnt know. Please experts Help me to get out of this error

6
  • 1
    move your @using (Html.BeginForm()) { on top of the <fieldset> and try.Still i dont think it would work cause all the fields are labels which wont get posted to the server. try adding a hidden fields in the form tag. Also for delete you dont need the entire object only the key should be enough. Commented Jun 17, 2014 at 12:46
  • hidden field trick work.I added sid in hidden field. But I does not understand why it happens? Have any idea @Nilesh Commented Jun 17, 2014 at 12:52
  • 1
    Check the answer from @Stephen . The DisplayFor generates <span> tags which are not input elements. When you submit a form only input fields are posted back with their current values. So in your case you are expecting a StudentModel as input to your action which will never work when you render <span>. Also as I mentioend when deleteing a record what you need is only the Id of the record to be deleted, so you can change your Delete(StudentModel student) method to Delete(int studentId) which should be enough. Commented Jun 17, 2014 at 12:56
  • yup I got it thanks Nilesh It is working fine Now :). I am newbie in MVC.. Trying to moving from asp.net to MVC. I hope One day I will learn MVC soon :) @Nilesh Commented Jun 17, 2014 at 12:59
  • 1
    Yup you will cause its really fun to develop apps in MVC. Am going the other way round though, from MVC to ASP.Net.:) Commented Jun 17, 2014 at 13:02

1 Answer 1

1

You do not have any inputs within you form element to post back (note Html.DisplayFor() methods do not render html inputs)

@using (Html.BeginForm()) {
  @Html.EditorFor(model => model.SID)
  @Html.EditorFor(model => model.StudentName)
  // Other properties here
  <input type="submit" value="Delete" />
}

If you don't want editable fields you can create hidden inputs for all properties or consider just posting back the ID and modifying you controller action

Sign up to request clarification or add additional context in comments.

4 Comments

okk means @Html.DisplayFor does not work for any type of editing ,deletition and updation? Am I right?
Yes, that correct. For post back you need <input...> (or <select..>) elements.
thanks stephen Its working fine now. But I am newbie in MVC can you give me any good refrence for study more?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.