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>
)
<%} %>
Related
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();
})
I have a view that is created within a MVC area.
from this view i want to add an Html form that gets to an action on a controller that is not in any Area but just in my main controller folder.
#using (Html.BeginForm("MyAction", "MyController", FormMethod.Get))
{
<input type="submit" value="TEST" />
}
When i execute this code it tries to find my controller in the same area and fails, following html is generated
<form action="/MyApp/en/MyController/MyMethod" method="get">
this actually works on other calls:
http://localhost:18183/MyApp/nl/OtherController/OtherAction
My action on the controller without area can be reached in the browser like this:
http://localhost:18183/MyController/MyMethod
But when i add the form the classic way it still doesn't work:
<form action="/MyController/MyMethod" method="get">
How can i achieve to call this controller?
You need to specify an annonymous object to the routeValues attribute:
#using (Html.BeginForm("MyAction", "MyController", new { area = "" }, FormMethod.Get))
{
}
If you wanted to go to a different area rather than no area, modify the empty quotes to be your new area
Documentation for this overload is available at http://msdn.microsoft.com/en-us/library/dd492933(v=vs.118).aspx
How can I update multiple DOM elements using Asp.Net Ajax?
This is my code:
<span id="status">No Status</span>
<br />
#Ajax.ActionLink("Update Status", "GetStatus", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "status" })
<br />
<br />
#using (Ajax.BeginForm("UpdateForm", new AjaxOptions { UpdateTargetId = "textEntered" }))
{
#Html.TextBox("textBox1", "Enter text")
<input type="submit" value="Submit" /><br />
<span id="textEntered">Nothing Entered</span>
}
UpdateTargetID takes a single string. Basically I want something like in WebForms we would write updatePanel2.update() and that panel too would update itself regardless of it's position. I know that can be achieved using Jquery. But I am trying to know if there is something available in the framework itself so I don't have to write repetitive code of Jquery on all pages of my project going forward.
But I am trying to know if there is something available in the
framework itself so I don't have to write repetitive code of Jquery on
all pages of my project going forward.
There is no native framework support for mutliple UpdateTargetId's in AJAX. You have to extend default behaviours to support multiple update areas.
What you can do is to make one AJAX call, get all the results in the format of Json. Then iterate the data on client side using JQuery and update the relevant areas on the page.
You could have your panel describe itself and have a javascript code reading those information and performing the update for you. For instance, you could use the data-* tags available in HTML5 and compatible with HTML 4.1.
Just to give you an idea :
<div class="autoUpdate" data-target="/Controller/UpdateAction" >
//..Some HTML content here.
</div>
<script>
function test() {
$(".autoUpdate").each(function(i, e) {
var target = $(e).data("target");
//...AJAX Query here will return HTML. Just replace innerHTML with AJAX response.
}
}
</script>
Or you could also simplify this by creating an updating panel widget in jQuery. It's simple enough to extend jQuery's functionalities.
I am trying to use ReCaptcha from Microsoft.Web.Helpers. If I load the entire page it renders correctly, but if I load the page with an ajax request it disappears.
Example (/home/index)
<div id="bla">
#Ajax.ActionLink("reload with ajax", "index", new AjaxOptions() { UpdateTargetId = "bla" })
#ReCaptcha.GetHtml(publicKey: "xxx")
</div>
If I enter /home/index the captcha appears. If I click the button reload with ajax the ReCaptcha disappears...
The page is loaded for the first time
reload with ajax was clicked, the contents of the page change to /home/index, in other words, the entire page reloaded asynchronous and the captcha is gone
Is there a way to fix this or a decent captcha helper for MVC 3?
I've replaced the helper with javascript. ReCaptcha script
<div id="captcha"></div>
<input type="submit" value="Send" />
<script type="text/javascript">
Recaptcha.destroy();
Recaptcha.create("publicKey", "captcha", {});
</script>
And the Controller is still the same
if (ReCaptcha.Validate("privateKey"))
{
}
So when it loads the view partially it executes this scripts and render correctly every time.
Thanks for the help #Bala R
I faced the same issue and the quickest solution i found is using what it is proposed above and add to it this part of code in the top of your page within the handler "EndRequestHandler" proposed by the .net javascript api ( http://msdn.microsoft.com/en-us/library/bb311028(v=vs.100)).
With this solution the backend validation always works.
Here is the code I've used :
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (Recaptcha != null) {
Recaptcha.destroy();
Recaptcha.create("public_key", "captcha", {});
}
}
</script>
I hope this could help someone...
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.