ASP.NET MVC3: Confirmation Box before submitting - c#

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

Related

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")

How to pass textbox value using #Url.Action in ASP.NET MVC Core 2.2

In my View i have the following code:
<input type="text" id="createdDate" placeholder="dd/mm/yyyy" />
Download
In my Control i have de following code:
[HttpGet]
public async Task<IActionResult> GetRoomAccessHistory(DateTime createdDate)
{
// TO DO
}
In this particular case, i want to pass the createdDate value that is inside the textbox (createdDate) to my Url.Action(...), so it could be passed as a queryString in my URL.
This action is invoked as a GET request, and in GetRoomAccessHistory control method, i should get my createdDate.
Thank you.
PS
I think the solution should be something like this:
<a href="#Url.Action("GetRoomAccessHistory", "Files", new { createdDate = ??? })" >Download</a>
I have got a possible answer:
<form method="post" enctype="multipart/form-data" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
...
<button type="button" id="downloadRoomAccessHistory"</button>
</form>
<script>
var form = document.getElementById("formGetRoomAccessHistory");
document.getElementById("downloadRoomAccessHistory").addEventListener("click", function () {
form.submit();
});
</script>
This does exactly what i want and it works, but i was trying to find a more nice solution because my experience in ASP.NET MVC is low.
You're using the wrong tool for the job.
Since the Url.Action() helper runs on the server-side, it has already executed when the page was first loaded, and generated a fixed URL which is inserted into the page's HTML. It cannot know what the user later enters into the textbox.
If you want to capture data which a user has entered, it makes more sense to use a form. In this case I've used the BeginForm tag helper to generate a suitable HTML <form> tag:
<form asp-action="GetRoomAccessHistory" asp-controller="Files" method="get">
<input type="text" id="createdDate" name="createdDate" placeholder="dd/mm/yyyy" />
<input type="submit" value="Download"/>
</form>
When submitted, this will generate a GET request to the GetRoomAccessHistory action's URL, and append createdDate as a querystring variable, using the value from the textbox.
For Get request,try to use window.location.href.
<input type = "text" id="createdDate" placeholder="dd/mm/yyyy" />
<a onclick = "navigate()" >
< input type="button" value='Download' />
</a>
<script type = 'text/javascript' >
function navigate()
{
var createdDate = document.getElementById('createdDate').value;
var url = "/Files/GetRoomAccessHistory?createdDate=" + createdDate;
window.location.href = url;
}
</script>
And your solution could be simplified to
<form method = "get" asp-controller="Files" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
<input type = "text" name="createdDate" placeholder="dd/mm/yyyy" />
<button type = "button" onclick="myFunction()">Download</button>
</form>
<script>
function myFunction()
{
document.getElementById("formGetRoomAccessHistory").submit();
}
</script>

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

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" })'"

How to use textbox event

I have a registration form and i want to do some thing like this: When user register and enter the username then check on database that this user is already in database or not.That's why when user enter username and move to another field then check it.
So please help me how to solve this and how use textbox events.
As you have not provided any markup i'm assuming the markup like this.
<form id="form1" action="~/something.aspx" method="post">
<label>Username</label>:
<input type="text" id="username" name="username" onblur="validate();"/>
<br/>
<label>Password:</label>
<input type="text" id="password" name="password"/><br/>
<input type="submit" value="submit"/>
</form>
The basic idea is that you need to write some javascript for username field when the focus is out(onblur event)
Here is the javascript for the above piece of code.
<script type="text/javascript">
function validate()
{
//make an ajax call to retrieve the username
$.ajax({
url:'validate.aspx/ValidateUsername',
dataType: 'json',
//... make necessary adjustments in ajax call so as to
//call the web method in validate.aspx page
success: function(data){
if(!data.d){
alert('username already exists !');
document.getElementById('username').focus();
}
}
});
}
</script>
Now defined your webmethod for the ajax call defined.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ValidateUsername()
{
//Now query the database to check if the username exists.
//If the username exists return 'true' other wise return 'false'
}
Hope this helps.
This is best done using AJAX rather than server-side events, this means you can POST asynchronously for a better UX e.g.
<script type="text/javascript">
var lookupTimer;
$('#username').change(function() {
clearTimer(lookupTimer); // cancel previous lookup if user types again
lookupTimer = setTimeout(function() {
$.post("myServer/checkUsername", { data: $(this).val() }, function(result) {
// handle result
});
}, 1000); // send query after 1 second when user finished typing
});
</script>
<input id="username" type="text" />

issue calling a c# function from jquery

I am attempting to call a function through a view using jquery.. originally i was using razor's #html.BeignForm but for the web it needs to be converted to jquery
i don't know if i'm on the right path, however this is what i have in razor that's currently working.
#foreach(var up in Model)
{
#up._id
using (#Html.BeginForm("DQPost", "Disqus", new { ID = up._id }, FormMethod.Post))
{
<h7>The thread ID</h7>
<input type="text" name="ThreadID" /><br />
<h7>The message </h7>
<input type="text" name="Message" /><br />
<input type="submit" value="Post Comment"/>
}
}
what i'm trying to do is change the submit to button that then fires off the jquery. and this is the jquery i currently have written out.
<script type="text/javascript">
$(document).ready(function () {
$('#post').click(function () {
var dataToSend = { ID: ID, MethodName: 'DQPost', Message: message };
var options =
{
data: dataToSend,
dataType: 'JSON',
type: 'POST',
}
});
});
</script>
any help would be greatly appreciated.
You are wrong here,$('#post').
$('#post').click(function () {
Post is not an identifier., so, you could declare your own. You could try something like
<input type="submit" id="submitButton" value="Post Comment"/>
Then,
$('#submitButton').click(function () {
will work fine.
Looks like you want to intercept the form submission so you can handle submit yourself with AJAX. If I'm reading that right, instead of attaching to the button's event, attach to the form's event:
$("#my-form-id").submit(function() {
// do my AJAX stuff
return false; // this will prevent the form from being submitted like normal
});

Categories

Resources