Pass arguments to a C# controller method using <button> and jquery - c#

I have a bootstrap modal which has many buttons which help to download files of different formats. I am able to enter the controller method when I use the set the onclick function as below:
onclick="location.href='#Url.Action("DownloadAsJPG", "Home")'"
I would like to do some condition based file downloading, based on the button that was pressed and hence I was thinking of passing a parameter as done here and here by setting the value attribute of the buttons
HTML :
<button type="button" id="tojpg" class="btn btn-outline-primary" value="jpg">JPG</button>
<button type="button" class="btn btn-outline-primary" value="jpgcmyk">JPG-CMYK</button>
<button type="button" class="btn btn-outline-primary" value="jpgrgb">JPG-RGB</button>
The argument in the controller method always remains null. I'm not sure what I have missed.
Controller method:
public FileResult DownloadAsJpg(string argument)
{ Some action }
I tried to play with a jquery which I found on a stackoverflow question which doesn't help me either, I couldn't reach the controller using this jquery.
Jquery
$('#tojpg').click(function (e) {
e.preventDefault();
window.location = '/Home/DownloadAsJpg?argument=' + $('#tojpg').val();
});
Any tips would be greatly appreciated.

If you can reach your controller with
onclick="location.href='#Url.Action("DownloadAsJPG", "Home")'"
and just want to pass some parameters. You can do that same was as
onclick="location.href='#Url.Action("DownloadAsJPG", "Home", new { argument = "tojpg" })'"
or with help of Jquery event
Edit
Try to wrap your event into $(document).ready(). By my experience, most of the time the reason for not working events is a that your buttons is not yet created when event binding happends.
$(document).ready(function() {
$('#tojpg').click(function (e) {
e.preventDefault();
location.href = '#Url.Action("DownloadAsJPG", "Home", new { argument = "tojpg" })';
});
}
And if you dont want to write a separate event for each button option you can create something like this.
<button type="button" class="btn btn-outline-primary" value="jpg">JPG</button>
<button type="button" class="btn btn-outline-primary" value="jpgcmyk">JPG-CMYK</button>
<button type="button" class="btn btn-outline-primary" value="jpgrgb">JPG-RGB</button>
and Jquery event like this
$(document).ready(function() {
$('.btn').click(function () {
location.href = '#Url.Action("DownloadAsJPG", "Home", new { argument = "'+ $(this).attr("value") +'" })';
});
}
That should work.

There are two ways of solving this:
Option 1
A <button /> is not part of the data that the form is posting. That is why it doesn't turn up at the server side. You should change this into an input like so:
<input type="submit" name="argument" value="jpg" />
The name of this field should be the same one as the name of the parameter in your action. Because this is an input-field, the browser will send the it with the entire post. This is what is being done in the posts you referred to.
Option 2
If you want to use window.location instead, then you need to make sure the action allows for a GET-request and that you pass in argument as the querystring:
onclick="location.href='#Url.Action("DownloadAsJPG", "Home", new { argument = "jpg" })'"

Related

Change boolean to false via button onclick method located in navigation bar

I want to change the following variable to false using the onclick method of a button in my shared navbar.
Variable
public static bool LoginStatus { get; set; } = true;
What I have so far which does not work:
Html button
<button type="button" class="btn btn-primary" onclick=#Apex_Leaderboard_Website.Models.LoginViewModel.LoginStatus = false>Log Out</button>
I have tried a form but with the button in the shared navbar it makes it difficult to submit it to the appropriate handler.
you should use asp:Button because you want to modify a C# class property. then you can OnClick event on it so that you will be able to call a backend(code-behind) method and in that method, you can set the enter code here to false.
Here is the reference for you.
You can use posting a form or use js.
<form method="post" asp-route-LoginStatus=false>
<input type="submit" value="Log Out" />
</form>
js:
<button type="button" class="btn btn-primary" onclick="passData()">Log Out</button>
function passData() {
$.ajax({
type: "POST",
url: "xxx",
data: { LoginStatus: false },
success: function(data) {
}
});
}
action:
public ActionResult xxx(bool LoginStatus)
{
....
}

ASP.NET JQuery, disabled a button on form submit not call httpPost action

I'm working in an ASP.NET MVC app and I want to disable a button when during OnSubmit event of the form, just for prevent double click of the users.
All JQuery part is working fine but I don't understand why, when I disabled the submit button, it always call the default Action of my controller.
Here is the cshtml code:
#using(Html.BeginForm()){
<input type="submit" value="Submit"/>
}
<script>
$(function(){
$("form").submit(e=>{
$('input[type="submit"]').prop("disable",true)
})
})
</script>
The JQuery part works and make the button disabled.
My controller:
public class MyController:Controller{
public ActionResult MyController(ExampleModel model){
return View(model);
}
[HttpPost,ActionName("MyController")]
public ActionResult FormSubmmit(ExampleModel model){
//Do some checks
return View(model);
}
}
The case is that if I make the button disabled, the form always call the action 'MyController' instead of the action FormSubmit (is which I want to call).
Do somebody know why can be the reason of this "error"?
try this
#Html.BeginForm("FormSubmit", "My", FormMethod.Post) {
<input type="submit" value="Submit"/>
}
and remove [HttpPost,ActionName("MyController")] from the action, it is a very strange attribute
This is a fast and reliable way of disabling the button to prevent any "Double click"
<form ... onsubmit="myButton.disabled = true; return true;">
...
<input type="submit" name="myButton" value="Submit">
</form>
You can see the source here
Another way of doing this when submitting is to do an overlay and then redirect
function(Optional, I use it to stop the overlay and just to basically inform the user that the function is done)
HTML:
<input type="submit" onclick="return FunctionOverlay(this);" />
<script>
function FunctionOverlay(btnElement)
{
showOverlay(btnElement);
$('#myForm').submit();
}
</script>
JS:
function showOverlay(buttonElement) {
$(buttonElement.parentNode).css('position', 'relative');
$bgColor = $(buttonElement).attr('data-overlay-color');
if ($bgColor === undefined) {
$bgColor = '#fff';
}
$(buttonElement.parentNode).append('<div class="button-overlay" style="background-color:' + $bgColor + ';"><img src="images/blahblah.gif" /></div>'); //.css('background-color', $bgColor)
}
You can use this to create your own overlay GIF
and then in your controller where you are calling the Method you can end it with
return View("ButtonClicked");
and in your home page create a cshtml ButtonClicked.cshtml
and just create a landing page where you can insert some text for example:
<div class="row">
<div class="col">
<p> Thank you for clicking😊</p>
</div>
</div>
Another option is doing an overlay with a timeout
$('form').submit(function () {
var button = $('#button');
var oldValue = button.value;
var isDisabled = true;
button.attr('disabled', isDisabled);
setTimeout(function () {
button.value = oldValue;
button.attr('disabled', !isDisabled);
}, 3000)
});
Firstable, thank for answer! And I just find the solution.
The problem of the code was if I use disabled it change the request metadata during the form submit event, so I can not make the button disabled.
I fount this solution, it just take off the pointer events from the button and then it prevent the double submit problem.
$('input[type="submit"]').css("pointer-events","none")

MVC Button element with parameters

How do I pass parameters to a controller action method with a button element?
This is not a form submit, I just want a button that is going to take you to another page, but the action method requires parameters.
I currently have:
<button type="button" class="btn btn-info" onclick='window.location = "#Url.Action("Index", "ReviewPendingApprovals", new object[] { Model.QuoteGuid })";'>
However, this results in empty HTML:
<button type="button" class="btn btn-info" onclick='window.location = "";'>
what exactly am I doing wrong here?
It's best to use an HTML helper for this.
#Html.ActionLink(
"ButtonText",
"Index", // controller action
"ReviewPendingApprovals", // controller
new { Model.QuoteGuid }, // action parameters aka route values
new { #class = "btn btn-info" }) // html attributes
RIGHT ANSWER HERE:
You did two things wrong: you didn't mark the onClick delegate as an href, and you didn't map the argument/route values to any parameter (but that didn't cause the render HTML markup to be blank)
I prefer to use input tags, but you can use a button tag
Here's what your solution should look like using HTML:
< input type="button" class="btn btn-info" onclick='window.location.**href** = "#Url.Action("Index", "ReviewPendingApprovals", new { **someParamHere** = Model.QuoteGuid })";'/>
I never tried to do it directly from a button, but when I use the controller to do it, it looks something like:
return RedirectToAction("ActionName", new { param1 = param1_value, param2 = param2_value });
so I suggest you try this:
<button type="button" class="btn btn-info" onclick='window.location = "#Url.Action("Index", "ReviewPendingApprovals", new object[] { object_name = Model.QuoteGuid })";'>
Try adding the URL Scheme parameter to Url.Action:
<button type="button" class="btn btn-info" onclick='window.location = "#Url.Action("Index", "ReviewPendingApprovals", new object[] { Model.QuoteGuid }, this.Request.Url.Scheme)";'>
You could code like this:
$('.btn-info').click(function (e) {
var url='#Url.Action("Index", "ReviewPendingApprovals",new { id= Model.QuoteGuid })';
window.location=url;
});
Use Jquery instead of onclick event:
$('button').click(function(){
winodw.location.href = '#Url.Action("Action","Controller",new{parameter name = value})';
});

Using ActionLink parameters with button onclick ?

Straight forword I think just can't find the syntax...
I have an ActionLink which uses an id property,
<td style="padding-right:35px">#Html.ActionLink("Edit", "EditUser", new { #id = user.ID.ToString("N") }, new { #class = "btn yellow"})</td>
Basically I want to change this to a btn, but I am not sure how to pass the id parameter , I think it's something like this....
<button type="button" class="btn blue" id="user.ID.ToString("N")" onclick="location.href='ReferralTarget/EditUser'"><i class="icon-edit"> Edit</button>
Where ReferralTarget is my control and EditUser my actionResult..
Please note this is an ASP.NET MVC4 application using Razor2 views...
Try something like this:
<button type="button" class="btn blue" onclick="location.href='#Url.Action("EditUser", "ReferralTarget", new { #id = user.ID }'"><i class="icon-edit"> Edit</button>
You could also do something like this if you like the jquery route:
#functions
{
private string GetUserId()
{
//I'm not sure where you are getting user from, but if it's from the model,
//you would need to change this to something like #Model.something....
return user.ID;
}
}
<script type="text/javascript">
$(document).ready(function() {
$('#edit').click(function() {
location.href = "ReferralTarget/EditUser/" + "#GetUserId()";
});
});
</script>
<input type="button" id="edit" value="edit" />
There is an easy trick-
Use jqueryUi, and justdo $("#linkid").button(), and style it how ever u want

ASP.NET MVC3: Confirmation Box before submitting

I have the following code which basically is a checkbox that causes a submit to take place.
As the task gets deleted for the DB, it is a requirement that some box comes up and says, "are you sure" or the likes, to confirm deletion.
<input type="checkbox"
onclick="location.href='#Url.Action("Complete", "Tasks",
new { TaskID = item.TaskID })'" />
This uses Razor syntax.
You could use the confirm method:
<input type="checkbox" onclick="if (confirm('Are you sure?')) { window.location.href = '#Url.Action("Complete", "Tasks", new { TaskID = item.TaskID })'; }" />
or in a more unobtrusive way with jquery:
<input type="checkbox" id="complete" name="complete" data-url="#Url.Action("Complete", "Tasks", new { TaskID = item.TaskID })" />
and then in a separate javascript file:
$(function() {
$('#complete').click(function() {
if (confirm('Are you sure?')) {
window.location.href = $(this).data('url');
}
});
});
Also I would very strongly recommend you using another verb than GET on controller actions that modify state on your server such as marking a task as completed. PUT, POST and DELETE are good candidates. In your case since you are modifying an existing item the POST verb seems most natural.
You may intercept the form submit event and ask confirmation. based on that return true or false to allow submit.
akin
$("#form").submit(function (event) {
if ( confirm("Are you sure you want to delete"))
return true;
else{
event.preventDefault();
return false;
}
});
It can be done this way
<input name="button" type="submit" value="Delete" class="btn btn-danger cancel" onclick="return confirm('Are you sure?')" />
hemant's solution didn't work for me. Moumit's solution did work but not when I moved the confirmation function to a named function in my page's javascript file - the confirmation button displayed but it was not prevented when I hit cancel (and as I write this, I wonder if I only needed to pass an event arg, call e.PreventDefault(), then return true).
Anyhow, here is yet another example, with a little help from JQuery, that did work in my aspnetcore mvc razor page:
$(function () {
$('#mySaveButton').click(function (e) {
e.preventDefault();
if (confirm('Are you sure?')) {
$('#myForm').submit();
}
});
});
I adapted this from a more complete example that is worked out from start to finish with an example project: how to show a confirmation dialog with jquery

Categories

Resources