Sumit
Sumit

Reputation: 3068

Deleting record using MVC Delete View

What I am trying to do is I am Listing all the record and then provide option to delete the record. When User clicks on Delete Link on Index page he is redirected to Delete Confirmation Page( Delete View created by MVC framework), now what I was expecting was when I click on Submit button on the Delete View it will come to my Delete Action of Controller with the object that needs to be deleted. But the problem is I am getting a object but all the properties are set to null.

Below is the code:

//GET
        public ActionResult DeleteUser (long id )
        {

            return View(_repository.GetUserById(id));

        }

        //POST
        [HttpPost]
        public ActionResult DeleteUser (UserDTO user)
        {

            _repository.DeleteUser(user.UserId);
            /
            return RedirectToAction("Index");
        }

I was expecting that one submit is clicked then Second (HttpPost) method will be called and user will be filled with the values, but that is not happening..

can anyone tell me what wrong am I doing ???

This is my Delete View Code

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<RepositoryPatternSample.DTOs.UserDTO>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    DeleteUser
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>DeleteUser</h2>

<h3>Are you sure you want to delete this?</h3>
<fieldset>
    <legend>UserDTO</legend>

    <div class="display-label">UserId</div>
    <div class="display-field"><%: Model.UserId %></div>

    <div class="display-label">Username</div>
    <div class="display-field"><%: Model.Username %></div>

    <div class="display-label">FirstName</div>
    <div class="display-field"><%: Model.FirstName %></div>

    <div class="display-label">LastName</div>
    <div class="display-field"><%: Model.LastName %></div>
</fieldset>
<% using (Html.BeginForm()) { %>
    <p>
        <input type="submit" value="Delete User" /> |
        <%: Html.ActionLink("Back to List", "Index") %>
    </p>
<% } %>

</asp:Content>

Upvotes: 1

Views: 6478

Answers (1)

Iridio
Iridio

Reputation: 9271

Your properties are out of the form post. That's why you see the model null. Personally instead of passing all the model properties I would pass only the id. Something like that

<% using (Html.BeginForm()) { %>
<p>
    <%: Html.HiddenFor(model=> model.UserId) %>
    <input type="submit" value="Delete User" /> |
    <%: Html.ActionLink("Back to List", "Index") %>
</p>
<% } %>

and your controller would be

[HttpPost]
public ActionResult DeleteUser (int userId)
{
   _repository.DeleteUser(userId);
   return RedirectToAction("Index");
}

Upvotes: 2

Related Questions