MVC Delete not hitting HttpPost Method - c#

I'm using MVC3. I learned that its a bad practice to delete an item using HttpGet Method as any one can browse to the url and deletes an item. So I want to perform delete operation on HttpPost Method.
The problem is that when I click delete button, it gets hit on HttpGet method only but not on HttpPost method.
I've used webgrid and its the index.cshtml file
<div id="DataTable">
#grid.GetHtml(htmlAttributes: new {id="gvMovies" },
columns:grid.Columns(
grid.Column("Title","Movie Title",canSort:true),
grid.Column("Director","Film Maker",canSort:false),
grid.Column(header:"Action",
format:#<text>
Edit
#using (Html.BeginForm("Delete", "Movies", new { id = #item.id }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ActionLink("Delete", "Delete", new { id = #item.id }, new { onclick = "return confirm('Are you sure you wish to delete this article?');" })
}
</text>)))
</div>
The controller page is as follows
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id)
{
return RedirectToAction("Index");
}

Conceptually it's not correct to use the POST verb for delete. POST - is intended for posting information. The correct way would be to to just remove the attribute from the Delete method, and let it go with the GET verb.
Now if you really really really need to use the POST, your first mistake is that you create a link, instead of a submit button that will submit the form. Replace
#Html.ActionLink("Delete", "De...
with:
<input type="submit" value="Delete">

you must add submit button instead of link so you must change
#Html.ActionLink("Delete" to <input type=submit value="del" >
if you want send id in the post you can add hidden input in the form so you can add some thing like this before your submit button in the form
<input type="hidden" value=#item.Id name="itemid" >
so i think this code will work
#using (Html.BeginForm("Delete", "Movies", new { id = #item.id }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="hidden" value=#item.Id name="itemid" >
<input type=submit value="del" >
}

Related

How do I call my method in html?

I want to call my method in my mvc view. I have a method called SavePersoon wich has to save the changed data into my database. This is my code from my services:
public bool SavePersoon(PersoonModel persoon)
{
bool result = true;
db.Persoon.AddOrUpdate(persoon.GetPoco());
db.SaveChanges();
return result;
}
This is the button who has to be pressed and then this code above has to deal the work itself.
The view:
<button type="button" id="btnSaveChanges" class="btn btn-primary">Opslaan</button>
Do I have to use something similair like <asp:LinkButton...?
You can make use of Ajax , Something like this
$("#btnSaveChanges").on("click",function(){
$.ajax({
url:"/controllerName/SavePersoon",
data:$("#formName").serialize(),
cache:false,
type:"POST",
error:function(){
alert("Error");
}
});
});
If you use Razor view engaine, you can make your method return an action result and call it from the view using Html.Actionlink.
You can do 2 things:
Use the HTML Helpers that ASP.Net MVC provides to create a form which posts to the required method, something like 'Save' of the controller 'Person':
#using (Html.BeginForm("Save", "Person", FormMethod.Post, new { #class = "form-horizontal" })) {
<div>
<!-- Your HTML, this could for example be a text field for the person its name -->
#Html.TextBoxFor(Model => Model.Name, new { #class = "form-control" })
<input type="submit" class="btn btn-primary" value="Save" />
</div>
}
This will create a form tag for you, something like <form action="person/save" method="post"> ... your HTML & the submit button ... </form>
An alternative is to use Ajax to prevent the page from refreshing as stated in the above post.
$("#btnSaveChanges").on("click",function(){
$.ajax({
url: '#Url.Action("Save", "Person")', // Again an MVC HTML Helper to create a URL
data:$("#Name").val(), // Posts the value of a text field with ID "Name"
cache:false,
type:"POST",
success: funcion(returnValue) {
// Do something with the result.
}
error:function(){
alert("Error");
}
});
});

Redirecting parent page from Html.renderAction child without using Ajax, Java, Jquery or such

I have a problem where I have a form in a Html.RenderAction and after submitting the form I have to reload the parent but I keep getting "Child actions can not perform redirect actions". So how can I solve it without Ajax etc.
In my parent I have:
#{
var UserReviewExist = Model.Reviews.FirstOrDefault(x => x.AspNetUser.UserName == Name.AspNetUser.UserName);
}
#{if (UserReviewExist == null)
{
Html.RenderAction("ReviewCreate", "Reviews", new { BookID = Model.Id });
}
}
My RenderAction View contains this:
#model Trigger_Happy_Bunnies.Models.Review
#{
Layout = null;
}
#{
if (true)
{
Trigger_Happy_Bunnies.Models.Review newReview = new Trigger_Happy_Bunnies.Models.Review();
<div style="border:1px black">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
and ends with
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
</div>
}
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
And lastly I have this in my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ReviewCreate([Bind(Include = "Id,BookId,UserId,Text,Title,Rating,IsActive,IsReported,ReportedBy,ReportReason,ModifiedDate,ModifiedBy,CreatedDate")] Review review)
{
if (ModelState.IsValid)
{
db.Reviews.Add(review);
db.SaveChanges();
return View("~/Views/Reviews/ReviewCreate.cshtml");
}
ViewBag.UserId = new SelectList(db.AspNetUsers, "Id", "Email", review.UserId);
ViewBag.BookId = new SelectList(db.Books, "Id", "UserId", review.BookId);
return PartialView();
}
So how can I update the parent view when submitting the form?
I'm not sure what your issue is here. A child action merely dumps its response into the view. So at the end of the day, whether you used a child action, a partial or just plopped the code right in the view, you just have a one HTML document that includes a form.
Calling Html.BeginForm with no parameters says basically that it should use the current action, but even in the context of child action, that's still going to be the main action being rendered. So, your form will post to that main action, not your child action.
That's how it should be. You cannot post to a child action, because that makes no sense in the context of a web page. Technically, you can as long as it's not marked as [ChildActionOnly], but the entire page will change to the partial view that's returned as the response, sans layout. If you want to replace just the area that was rendered via the child action, you must submit an AJAX request that returns the partial response and manually replace the appropriate node in the DOM with that.
In other words, that's why a child action can't redirect. It's not a true action and it hasn't been routed to. It's not rendered until the response preparation phase, and by that point, there's already data in the response, preventing any changes, like a redirect. If you need to redirect after the post of the form, you should have that already in place, just make sure your main action has a version that handles post, and redirect from there.

Last input values passed to action in MVC

I want to generate table with, for example, 4 columns. In last column i need link to remove user whitch is in that row. When i am using form tag like this:
#foreach (var item in Model.Approvers)
{
<tr>
<td>#item.FullName</td>
<td>#item.Email</td>
<td>#item.AdAccount</td>
<td>
<form id="removeApproverRoleForm" action="~/Admin/RemoveRole" method="post">
#Html.AntiForgeryToken()
<input type="text" id="userId" name="userId" value="#item.Id" />
<input type="text" id="role" name="role" value="Approver" />
Remove
</form>
</td>
</tr>
}
It passes last value of userId and role to RemoveRole method. It have to be POST method so this whould not work:
#Html.ActionLink(Remove, "RemoveRole", "Admin", new { role = "Approver", userid = item.Id }, new { onclick = "return removeRole();" })
Even if i place form tag above that, the parameters are still visible in the link.
So i need somehow use new { role = "Approver", userid = item.Id } but send it as a POST and hide those values.
Any ideas?
Thank you for help!
It is a popular problem, so you can find detailed solution here
Short answer is:
use <input type="submit">Remove</input> inside the form
OR use
#Ajax.ActionLink("Remove, "RemoveRole", "Admin", new { role = "Approver", userid = item.Id }, new AjaxOptions { HttpMethod = "POST" })
to be able to create ActionLink with controlling the method parameter.

MVC 4 Form submission doesn't result in desired url parameters

I'm trying to use a form to allow the user to pick a date and pass it back to the controller by way of url parameters. My intention is to have the form submit a url that looks like Payroll/Index/id?employeeID="foo"?DayInWeekInput="bar". Instead this generates the url Payroll/Index/id? so I'm obviously doing something wrong. How can I do this with a form? If it's not possible, could you explain an alternative? Thanks.
using (Html.BeginForm("Index", "Payroll", new { id = #ViewBag.SupervisorID, employeeID=#ViewBag.EmployeeID }, FormMethod.Get))
{
#*#Html.AntiForgeryToken()*#
#Html.ValidationSummary(true)
<div class="editor-field">
<input type="date" id="DayInWeekInput" value="#string.Format("{0:yyyy-MM-dd}", Model.SpecifiedWeekStart)" />
<input type="submit" value="Go" />
</div>
}
you stopped naming, if you keep the names up it should work for you
using (Html.BeginForm("Index", "Payroll", new { id = #ViewBag.SupervisorID, EmployeeID = #ViewBag.EmployeeID, DaysInWeekInput = "bar" }, FormMethod.Get))
Since that didn't work for you I would try an ajax call next
$('.btnSubmit').on('click', function(){
$.ajax({
url: '#Url.Action( "Index", "Payroll" )',
data: {
id: #ViewBag.SupervisorID,
EmployeeID: #ViewBag.EmployeeID
},
success: function (_result) {
if (_result.Success) {
}
}
});
});
I would also recommend putting your id's in hidden fields. Viewbag can be unstable.

Event Asp Mvc Redirect

I am beginner in asp.net mvc. I have in the view Home.cshtml
<button name ="del" style="width:150px; height:30px;text-decoration:none;color:white;text-align:center;background-color:darkcyan;padding:5px;border-style:outset;border-width:2px;border-color:darkcyan" onclick="#Url.Action("Delete", "Super",1)">Supprimer</button>
<button name ="edit"style="width:150px; height:30px;text-decoration:none;color:white;text-align:center;background-color:darkcyan;padding:5px;border-style:outset;border-width:2px;border-color:darkcyan" onclick="#Url.Action("Edit", "Super","val")">Editer</button>
When i click into the two buttons nothing is gone and the redirection didn't work.
why?
How can i change it to be correct?
You don't want to be creating links like this in MVC. Try using ActionLink:
#Html.ActionLink("Delete", "Edit", "Super");
#Html.ActionLink("Edit", "Edit", "Super");
http://msdn.microsoft.com/en-us/library/system.web.mvc.html.linkextensions.actionlink(v=vs.108).aspx
For a button:
<input type="button" value="Supprimer" onclick="window.location.href='#Url.Action("Delete", "Super")';" />
To specify parameters:
<input type="button" value="Supprimer" onclick="window.location.href='#Url.Action("Delete", "Super", new { Id = 1 })';" />
You can use JQuery in this case to improve the current quality of code as below
<input id="supprimer" type="button" value="Supprimer" />
$('#supprimer').click(function(){
window.location.href = '#Url.Action("Delete", "Super")';
});
And in the best version, try to module that code with the AMD pattern
The problem is that the onclick is a javascript event, and thus requires javascript code. You are just setting it as a URL, which will do nothing.
One option (and I am not saying it is the best) would be to change it to:
onclick="window.location = '#Url.Action("Delete", "Super", new { id = 1 })';"
I found this solution :
<a type="button" style="width:150px; height:30px;text-decoration:none;color:white;text-align:center;background-color:darkcyan;padding:5px;border-style:outset;border-width:2px;border-color:darkcyan;margin-left:25px" href="#Url.Action("Delete", "Super",new { Id = 1 })">Supprimer</a>
<a type="button" style="width:150px; height:30px;text-decoration:none;color:white;text-align:center;background-color:darkcyan;padding:5px;border-style:outset;border-width:2px;border-color:darkcyan" href="#Url.Action("Edit", "Super",new { Id = 1 })">Editer</a>
In the controller:
public ActionResult Edit(int id)
{
int id2 = id;
return RedirectToAction("Edit", "Admin", new {id = id2});
}

Categories