I have a form in C# ASP, and two buttons submit with different path.
<form asp-action="">
<button type="submit" data-action="Liquidation" class="btn-method-switchable">
<button type="submit" data-action="Return" class="btn-method-switchable">
I try to modify the path with Jquery like that :
$('.btn-method-switchable').click(function(e) {
e.preventDefault();
let value = $(this).data('action')
$('form').attr('asp-action', value);
$('form').submit();
})
I enter in my Controller but not on the method Liquidation or Return.
Thanks for your answers
The asp-action attribute is only used before rendering. When the page is rendered it's converted to a standard HTML form action attribute.
Also note that on the client side its value is converted from the reference to the action name to a relative URL to the route. More detail on that in the documentation.
Therefore to correct your code you need to set the action attribute and also amend data-action on the button elements to be the full route. This can be done using the Url.Action() helper. The code would look something like this:
<form>
<button type="submit" data-action="#Url.Action("Liquidation")" class="btn-method-switchable">Foo</button>
<button type="submit" data-action="#Url.Action("Return")" class="btn-method-switchable">Bar</button>
</form>
$('.btn-method-switchable').click(function(e) {
e.preventDefault();
let value = $(this).data('action')
$('form').attr('action', value).submit();
})
Related
I have following Razor code:
<form method="post" asp-controller="Cryptocurrency" asp-action="DeleteWatchedProduct">
<button type="submit" name="id" value="#providerItem.Item.Id" class="btn btn-danger">Delete</button>
</form>
and following action
[HttpPost("watched-product/{id}")]
public IActionResult DeleteWatchedProduct([FromRoute]string id)
{
return RedirectToAction("WatchedProducts",new
{
deletedId = id
});
}
When I hit the Delete button, it sends request to https://localhost:5003/cryptocurrency/deletewatchedproduct but desired target URL is https://localhost:5003/cryptocurrency/watched-product/id-is-here
How can I set it up?
Try to set the asp-route-id attribute for the form tag instead of defining it in the button.
The asp-route-{value} attribute enables a wildcard route prefix. Any
value occupying the {value} placeholder is interpreted as a potential
route parameter. If a default route isn't found, this route prefix is
appended to the generated href attribute as a request parameter and
value.
<form method="post" asp-controller="Cryptocurrency" asp-action="DeleteWatchedProduct",
asp-route-id="#providerItem.Item.Id">
I have a simple Web Application in C#.
In Index.cshtml file, I want to insert a button, and when I click on it, call a method of my Controller.
So I wrote this code:
<div class="row" style="float:left;width:100%;height:100%;">
<div class="col-md-12" style="width:100%;height:100%;">
#using (Html.BeginForm("action", "IndexController"))
{
<input type="submit" value="Create" />
}
</div>
</div>
In my controller I'm build this code:
[HttpPost]
public ActionResult MyAction(string button)
{
return View("TestView");
}
But if I try to click on button the application does not call method MyAction.
ASP.NET MVC convention requires the action name be used and the controller name minus "Controller" so, since your action method's name is "MyAction" and your controller's name is "IndexController", update the call like this:
#using (Html.BeginForm("MyAction", "Index"))
Update based on comment:
To send text to your action method to satisfy the string button parameter, you can include an input field in your form like this:
#using (Html.BeginForm("MyAction", "Index"))
{
<input type="text" name="button"/>
<input type="submit" value="Create" />
}
note that the name attribute of the text field is "button" to match the string button parameter name.
i'd suggest that another name other than button might be good, but whatever the name of your parameter, the input field that has a matching name attribute will supply the value to that parameter.
I'm using umbraco with extensionless urls.
I've inserted a simple piece of HTML in one of my masterpages (en/test) :
<form method="post" enctype="multipart/form-data">
<input type="submit" />
</form>
When I press the submit button, I get a 404. The path is exactly the same and should exist.
When I remove the enctype part, the submit occurs fine.
I can't figure out how to fix this, but I bet it has something to do with the rewriting.
I also tried the following without success:
<form method="post" enctype="multipart/form-data" action="/en/test">
<input type="submit" />
</form>
<form method="post" enctype="multipart/form-data" action="/en/test.aspx">
<input type="submit" />
</form>
The only page where I CAN use the enctype attribute, is on the actual homepage. I guess this has to do with the fact that the physic default.aspx exists.
=============== UPDATE =================
There is only one form element in the page, the one that I've inserted. So a "whole page" form element is certainly not the case. Secondly, yes the form is in theory posting back to itself. I also tried an empty action tag, plus an action tag with the full url as suggested, with the same results.
When I either use the following scenario's:
No action attribute
action=""
action="{relative path}"
action="{absolute path}"
I end up on exact same URL as where I fired the submit from. But it's a 404. When I press the enter key in my address bar, no 404, I'm back at my original page with the same URL.
First question I should ask is do you get a 404 when you browse to "/en/test" or "/en/test.aspx". For the form to post back to itself try an empty action e.g. action="" or writing the current url into the action attribute. And one further question, do you have another form wrapped around your page with the runat="server" attribute because if you have you will end up with nested forms which will also cause you issues.
On a side node I would strongly suggest upgrading your installation to at least v4.11.4 due to a bug that was introduced in 4.10. Please see the following for details...
Trying to publish a root node (parent) after unpublishing a child result in a YSOD:
http://issues.umbraco.org/issue/U4-1491
Path Fixup
http://our.umbraco.org/projects/developer-tools/path-fixup
I'm checking to see if anyone has written an MVC extension for Html.ActionLink that you can pass in Post parameters like such:
<% Html.ActionLink("Click me", "Index", "Home", new { MyRouteValue = "123" }, null, new { postParam1 = "a", postParam2 = "b" }); %>
That would render the link like normal but having an onClick event that submits an also rendered form with an Action url for the Action, Controller, and Route Values with additional hidden inputs from the Post Parameters like such:
Click me
<form id="theform" action="/Home/Index/123" method="post">
<input type="hidden" name="postParam1" value="a">
<input type="hidden" name="postParam2" value="b">
</form>
I'm looking to redirect users to various pages with potentially a lot of data. Not only from page to page, but from email to page also. This would be highly reusable and I think would clean up a lot of code, and would save a bunch of time writing this if its already floating around out there. I hate recreating the wheel when I don't have to.
ActionLink is just for creating an <a>. What you are asking for would blow up if it is already inside of a form. If it isn't then it is preferable to make the link the submit button inside the form and NOT use javascript (javascript and emails don't get along great).
You could create the form and appende it to the end of the DOM. This could be done through partial view or through javascript.
Honestly I suggest you don't use a POST. If you persist most of the data and just have the ids needed to retrieve said data, you should never have to pass too much data in an actionlink.
Ajax.ActionLink works perfectly fine for a post request. To refresh page, you can create a function that refreshes page (e.g. function reload(){ windows.location.reload();}).
It would look something like this.
#Ajax.ActionLink("DiaplyName", "Action", new { parameters to post }, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, OnComplete="reload();"})
Note: You'll need to reference the appropriate scripts to use ajax or jQuery code.
This piece of code was helpful for me and saved my day.. I improved it and it helped me for Impersonated user.. here is bellow ,what i did..
<% if (Session["SessionUserImpersonate"] != null && Session["SessionUserImpersonate"] != "" && Session["SessionUserImpersonate"] == "Yes")
{
BLL.Models.User userold = new BLL.Models.User();
userold = (BLL.Models.User)Session["SessionUserOld"];
%>
<span class="FL">(Impersonated as <%=Website.Backoffice.SessionHelper.Session_User.UserName != null ? Website.Backoffice.SessionHelper.Session_User.UserName:"" %> , </span>
<form class="FL" id='frmid' action="/Index/Login?username=<%=userold.UserName%>&password=<%=userold.Password%>&IsImpersonate=No" method="post">
<a class="TxtRed" style="cursor:pointer;" onclick="$('#frmid').submit(); return false;" > - finish impersonated session </a>
</form>
)
<%} %>
I am unable to determine which form submit button is clicked during an Ajax Form POST in ASP.NET MVC. I have a form that basically looks like:
<% using (Ajax.BeginForm("Edit",
new { code = Model.Code },
new AjaxOptions() {
UpdateTargetId = "resultsDiv"
})) {%>
<p>
<%= Html.TextBox("Name", Model.Name)%>
<input id="submitButton1" name="submitAction" class="ajaxSubmitButton"
type="submit" value="Button 1" />
<input id="submitButton2" name="submitAction" class="ajaxSubmitButton"
type="submit" value="Button 2" />
<input id="testHiddenValue" name="testHiddenValue"
type="hidden" value="hello world!" />
</p>
<% } %>
After a standard HTTP POST (ie. JavaScript disabled), I get access to the following POST variables:
Name = whatever
submitAction = Button 1
testHiddenValue = hello world!
However, clicking that button with JavaScript enabled does not include the submitAction value. I have verified this by inspecting the POSTs with Fiddler.
My hunch is that the Microsoft Ajax library just doesn't serialize the values of the submit buttons. In any case, how can I get around this so my controller knows which button was clicked?
Edit: Yes, it looks like a bug in the Microsoft Ajax library (see below). To workaround this, I essentially added the following jQuery code:
$(document).ready(function() {
$("#formId .ajaxSubmitButton").live("click", function() {
$("#testHiddenValue").attr("value", $(this).attr("value"));
});
});
Then in my controller, if Request.IsAjaxRequest() == true, I can check the value of #testHiddenValue. Otherwise, I can look in Request.Form["submitAction"] and determine the correct course of action from there.
Fairly clunky, but I can't really see an alternative.
See here. It looks like this is a bug. Personally I would investigate injecting the button name you wish to know about into a hidden form field as a temporary fix.