Reputation: 303
Using Razor pages for my views, I can't find a way to pass an Id / bounded model to my controller.
I have created a delete template view with my model, added a delete action method to my controller, but I can't figure out how to pass any parameters.
@model AdventureWorks.Models.HumanResources.Department
@{
ViewBag.Title = "Delete";
}
<h2>Delete</h2>
@using (Html.BeginForm("DeleteConfirmed", "Department", FormMethod.Post))
{
@Html.AntiForgeryToken()
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>Department</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Name)
</dt>
<dd>
@Html.DisplayFor(model => model.Name)
</dd>
<dt>
@Html.DisplayNameFor(model => model.GroupName)
</dt>
<dd>
@Html.DisplayFor(model => model.GroupName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ModifiedDate)
</dt>
<dd>
@Html.DisplayFor(model => model.ModifiedDate)
</dd>
</dl>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Delete" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Controller
public ActionResult DeleteConfirmed(Department department)
{
return ViewDepartments();
}
The Department object that is returned, is a new object with no properties set.
Could you advise me, how to pass at least an Id of the to be deleted object? I managed to get the model with the form on my create and update method, but I can't figure out, how to do the same on delete.
Upvotes: 2
Views: 2824
Reputation: 18159
You can add the parameters you want to pass in Html.BeginForm.Here is a demo:
@using (Html.BeginForm("DeleteConfirmed", "Department",new { Id=Model.Id}, FormMethod.Post))
{
...
}
result:
And you don't need to add @Html.AntiForgeryToken()
,because your form method is post.
Upvotes: 2
Reputation: 3208
You have to pass some value to your controller.
@using (Html.BeginForm("DeleteConfirmed", "Department", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(m => m.Id) // Use valid expression for id property
...
}
And change signature of DeleteConfirm method to
public ActionResult DeleteConfirmed(int id) // Use valid id property type
{
// Delete object
}
That should do the trick.
Upvotes: 0
Reputation: 43860
DisplayFor will not do the Model binding.
Assuming Id is a key of Department, add
@Html.HiddenFor(model => model.Id)
inside of Html.BeginForm.
Inside of you delete action use department.Id to find and delete the item.
Upvotes: 0