How to create the confirm box in mvc controller? - c#

I need to create the confirm box in mvc controller?. Using this 'yes' or 'no' value I need to perform the action in my controller. How we do that?
Sample code:
public ActionResult ActionName(passing value)
{
// some code
message box here
if (true)
{ true code}
else { else code}
}

You can do this with ActionLink
#Html.ActionLink(
"Delete",
"DeleteAction",
"Product",
new { confirm = true, other_parameter = "some_more_parameter" },
new { onclick = "return confirm('Do you really want to delete this product?')" })
If user confirm, then link parameter will pass to the controller action method.
public ActionResult DeleteAction(bool confirm, string other_parameter)
{
// if user confirm to delete then this action will fire
// and you can pass true value. If not, then it is already not confirmed.
return View();
}
Update
You can not show message box in controller side. But you can do this like following
public ActionResult ActionName(passing value)
{
// some code
message box here
if (true){ ViewBag.Status = true }
else { ViewBag.Status = false}
return View();
}
And view
<script type="text/javascript">
function() {
var status = '#ViewBag.Status';
if (status) {
alert("success");
} else {
alert("error");
}
}
</script>
But these all codes are not elegant way. This is solution of your scenerio.

Yes, you can do this with #Html.ActionLink as AliRıza Adıyahşi has commented.
Subscribe to the onclick event of the #Html.ActionLink
Here is the implementation:
#Html.ActionLink("Click here","ActionName","ControllerName",new { #onclick="return Submit();"})
And in javascript write the confirm box.
<script type="text/javascript">
function Submit() {
if (confirm("Are you sure you want to submit ?")) {
return true;
} else {
return false;
}
}
</script>
Edit
Try like this:
<script type="text/javascript">
function Submit() {
if (confirm("Are you sure you want to submit ?")) {
document.getElementById('anchortag').href += "?isTrue=true";
} else {
document.getElementById('anchortag').href += "?isTrue=false";
}
return true;
}
</script>
#Html.ActionLink("Submit", "Somemethod", "Home", new { #onclick = "return Submit();", id = "anchortag" })
Now in your controller do some operations based on the isTrue querystring
public ActionResult Somemethod(bool isTrue)
{
if (isTrue)
{
//do something
}
else
{
//do something
}
return View();
}

You dont create confirm box in a Controller, but yes in a View, using JQuery Dialog.
The Controller is already inside the server, so you don't have user interactions there.
Your View, in the other hand, is the place where the user will choose options, type information, click on buttons etc...
You can intercept the button click, to show that dialog, and only submit the post when the option "Yes" gets clicked.
JQuery Dialog requires jquery.js, jquery-ui.js, jquery.ui.dialog.js scripts referenced in your page.
Example:
$(function(){
$("#buttonID").click(function(event) {
event.preventDefault();
$('<div title="Confirm Box"></div>').dialog({
open: function (event, ui) {
$(this).html("Yes or No question?");
},
close: function () {
$(this).remove();
},
resizable: false,
height: 140,
modal: true,
buttons: {
'Yes': function () {
$(this).dialog('close');
$.post('url/theValueYouWantToPass');
},
'No': function () {
$(this).dialog('close');
$.post('url/theOtherValueYouWantToPAss');
}
}
});
});
});

I can confirm that AliRıza Adıyahşi's solution works well.
You can also customize the the message. In my case we're using MVC and Razor, so I could do this:
<td>
#Html.ActionLink("Delete",
"DeleteTag", new { id = t.IDTag },
new { onclick = "return confirm('Do you really want to delete the tag " + #t.Tag + "?')" })
</td>
Which showed a dialog with a specific record named in it. Might also be possible to give the confirm dialog a title, haven't tried that yet.

<a href="#Url.Action("DeleteBlog", new {id = #post.PostId})" class="btn btn-sm btn-danger" onclick="return confirm ('Are you sure want to delete blog?');">
<i class="glyphicon glyphicon-remove"></i> Delete

Related

MVC ActionLink calling multiple JQuery functions

I'm trying to call a confirm, then an alert function from an MVC action link and I'm stuck. The code is as follows:
My view has the following actionlink:
#Html.ActionLink("JQuery Testing", "BuildProject", Model, new { onclick = " return ConfirmProjectSubmit()" })
which calls the controller to save a project to the database. I'm trying to throw a confirm statement onClick. Once that action is performed, the following action is called:
return RedirectToAction("ProjectDetails", "Project", new RouteValueDictionary(new { id = currentProject.Id, msg = message }));
to alert the user that the project was actually created.
and then at the bottom of my view:
#section scripts {
<script type="text/javascript">
function ConfirmWorkflowSubmit() {
$.confirm({
title: 'Confirm!',
content: 'Simple confirm!',
buttons: {
confirm: function () {
},
cancel: function () {
}
}
});
return false;
};
</script>
#if (ViewBag.message != null)
{
<script type="text/javascript">
$(document).ready(function () {
$.alert({
title: 'Workflow successfully created',
content: '#ViewBag.message',
type: 'green',
});
});
</script>
}
}
both of the actions are firing, but incorrectly. I'm newer to MVC and moreso to Jquery. Basically I need to figure out how to not have it submit if the user doesn't confirm, and then make sure the message only pops on the way back. I think I just need help ordering what I have properly.
Thanks in advance.
EDIT. Okay, so I see part of the problem. It's not the $confirm function that's actually submitting the form, it's the button action clicked once the dialog is open. I'm really stuck here, and this has to be easier than I'm making it. Help!
I'm not saying you can't do it the way you have, but this is normally how I set up my bindings:
$(document).ready(function ()
{
// add the e here -- it is the event which initiated the binding
$(".buildButton").on("click", function (e)
{
if (ConfirmProjectSubmit())
{
alert('confirm');
}
else
{
// e.preventDefault() cancels the click action
e.preventDefault();
alert('cancel');
}
});
});
function ConfirmProjectSubmit()
{
// some confirm logic
// return true for confirmed, false for cancelled
return false;
}
Remove the onclick in your action. There is no need to have a jQuery binding and an onClick.
This is sort of an outline, you can add your logic in various places to finish it out.

Deleting a file from server on button click in ASP.NET MVC

I'm not well versed in this framework so I need some help here. In a view I want to add a link or a button on clicking which a certain file gets deleted from the server.
I've added this method to the controller:
[Authorize]
public ActionResult DeleteFile(string path)
{
if ((System.IO.File.Exists(path)))
{
try
{
System.IO.File.Delete(path);
}catch(Exception ex)
{
Debug.WriteLine("Deletion of file failed: " + ex.Message);
}
}
return View();
}
Seemed straightforward, though I'm not sure about the return View();. Now in the view, I need a form, because the path to the file that should be deleted needs to be posted to the controller, is that correct? This is what I got so far, mimicked from other code in the project:
#Html.BeginForm("DeleteFile", "Home", FormMethod.Post, new { id = "delete-attachment-form" })
{
#Html.Hidden("path", path)
}
path is a JavaScript variable containing the server path to the file that needs to be deleted. If I'm on the right track here, how do I add a button or a link to click on that will send the form?
Should just be able to add a submit button:
<input type="submit" name="submit" />
You should have a form and a button like this
#Html.BeginForm("Controller", "DeleteFile", new {Path= filePath},FormMethod.Post)
{
//Button
}
Or using Ajax and Jquery
var values = $(this).serialize();
$.ajax({
type: 'POST',
url: "url?path="+path.tostring(),
data: values ,
success: function(response) { //update view }
});
Inside your form you can add a button and then handle the button click in JavaScript.
#Html.BeginForm("DeleteFile", "Home", FormMethod.Post, new { id = "delete-attachment-form" })
{
#Html.Hidden("path", path)
<button id="delete-btn" type="button" class="btn btn-danger">
Delete
</button>
}
Then the <script type="text/javascript"> block:
$(function () {
$('#delete-btn').click(function () {
var query = $('#delete-attachment-form');
var form = query[0];
var toPost = query.serialize();
$.ajax({
url: form.action,
type: form.method,
data: toPost,
success: function (result) {
// display result
},
error: function () {
// handle error
}
})
});
});
Also, this is a good tutorial on deleting in ASP.NET MVC

process to mvc action after jquery confirmation button is clicked

I'm trying to implement jquery onclick confirmation dialog to my mvc3 delete actions.
Worth to mention is that I'm succ. render dialog itself, where I'm struggle is process action to /User/Delete action from js after the continue button is clicked. Here's the code:
onclick-delete.js
$(function () {
var deleteLinkObj;
// delete Link
$('.delete').click(function () {
deleteLinkObj = $(this); //for future use
$('#delete-dialog').dialog('open');
return false; // prevents the default behaviour
});
//definition of the delete dialog.
$('#delete-dialog').dialog({
autoOpen: false, width: 400, resizable: false, modal: true, //Dialog options
buttons: {
"Continue": function () {
$.post(deleteLinkObj[0].href, function (data) { //Post to action
// THIS IS WHERE I SHOULD SEND DATA TO MY DELETE ACTION (Users/Delete)
else {
alert("error");
}
});
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
});
So, what I'm doing wrong.
After clicking error is thrown, any ideas
Correct me if I wrong, but isn't this way simpler and more effective
#Html.ActionLink("Delete", "Delete",
new { id = item.Id },
new { onclick = "return confirm('Are you sure you wish to delete this article?');" })
As per the discussion in Mark Oreta's answer, here's what I would do:
If you set up the form like always, you can still get confirmation from the user without too much hassle. Take the following HTML/JS:
<form action="/User/Delete" method="post">
<!-- some fields here -->
<input id="btnSubmit" type="submit" value="Delete" />
</form>
This should properly submit the form to the backend. Interesting to note is that if you click the submit button, any click event set up in javascript/jQuery will be executed before submitting the form.
So you can do:
$("#btnSubmit").click(function(event) {
event.preventDefault(); // --> This stops the form submit from happening.
});
If all you need is a textbox in which the user confirms, there is no need to use anything other than the standard confirm() function. This messages the user and asks him to either agree or cancel. The function returns true/false according to the user's response.
So you can write the simplest of code:
$("#btnSubmit").click(function(event) {
var confirmationmessage = "Are you sure you want to delete this?";
if( ! confirm(confirmationmessage) ) {
// !confirm == the user did not confirm. Therefore stop the form submission.
event.preventDefault(); // --> This stops the form submit from happening.
} else {
// The user agreed. There is no else block needed, then normal form submission may occur.
}
});
This code is much simpler and easier to read than the snippet in your question. Of course, if you prefer using any other means of asking confirmation from the user, that works too. Just make sure you end up with an if(someboolean) { event.preventDefault(); } at the end of it.
I've created a JSfiddle for you here
I'm hoping you pulled out some relevant code, because your post function was setup incorrectly. I got it working like this:
$(function () {
var deleteLinkObj;
// delete Link
$('.delete').click(function () {
deleteLinkObj = $(this); //for future use
$('#delete-dialog').dialog('open');
return false; // prevents the default behaviour
});
//definition of the delete dialog.
$('#delete-dialog').dialog({
autoOpen: false, width: 400, resizable: false, modal: true, //Dialog options
buttons: {
"Continue": function () {
$.post(deleteLinkObj[0].href, function (data) {
//do the data parsing here
alert(data);
});
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
});​
Where you see do the data parsing here is where you need to handle what your controller is returning. Normally, when I do something like this, my return from the delete action on the controller is a boolean value, so that in the Jquery above, you could do something like
if (data == true)
alert("success!");
else
alert("error");
Try this:
<script type="text/javascript">
$(document).ready(function () {
$('form[action$="/Delete"]').submit(function () {
return confirm('Are you sure you want to delete ?');
});
});
</script>
Think that's about all, using jQuery events.. http://api.jquery.com/submit/

Knockout wizard with Asp.net MVC3

I have a wizard like this: http://jsfiddle.net/rniemeyer/FyuSD/ when I click button next data of current step are send to the server (the function to send data its not display in this link ) in the server i have an action like this:
Controller:
[HttpPost]
public ActionResult SocialNetworkChoice(string[] selectedSocialNetwork)
{
if (selectedProduct!= null)
{
// check if the user got a social account linked in for
// all the selected networks and redirect to the link account page
....
if (q.Count() > 0)
{
return RedirectToAction("LinkAccount", "Account",
new LinkAccountModel() { ProviderName = q.First() });
}
else
{....}
}
}
Knockout:
<script id="socNetchoiceTmpl" type="text/html">
<ul data-bind="foreach: socialNetworksList, visible:
socialNetworksList().length > 0">
<li>
<input type="checkbox" data-bind="value: $data, checked:
$parent.selectedSocialNetworks" /><span data-bind="text: $data"/>
</li>
</ul>
</script>
function SocialNetChoicesViewModel() {
var self = this;
self.socialNetworksList = ko.observableArray([]);
self.selectedSocialNetworks = ko.observableArray([]);
self.save = function () {
$.ajax("/Home/SocialNetworkChoice", {
data: ko.toJSON({ selectedSocialNetworks: self.selectedSocialNetworks }),
type: "post", contentType: "application/json",
success: function (result) {
if (result.Success) {
//alert(result.Message);
}
else {
alert(result.Message);
}
}
});
};
// Load initial state from server, convert it to Task instances,
// then populate self.tasks
$.getJSON("/Home/SocialNetworkChoice", function (allData) {
var mappedItems = $.map(allData, function (item) { return item });
self.socialNetworksList(mappedItems);
});
};
in the first step i have two checkbox for two social networks, when a user check ckeckbox data its send to the action SocialNetworkChoice.
if (q.Count() > 0) the view for action "LinkAccount" doesn't display and the wizard pass to the second step
How can to solve this probleme if (q.Count() > 0) redirect to LinkAccount (View) else to second step
I'm sorry for my bad english,
thanks,
Your are only redirecting the ajax call, not the visible page.
One solution is to detect the redirected ajax call and programmatically redirect the page accordingly. E.g. set window.location from javascript.

ASP.NET MVC Form loaded via ajax submits multiple times

I have a partial view containing an ajax form. This partial view is loaded onto my page via an ajax call. I can edit the fields and submit the form and everything works normally. However, if I reload the form N times, the form will submit N times when the save button is clicked.
here is the code for the partial view....
#model blah blah...
<script src="#Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript</script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"type="text/javascript"></script>
<div id="modalForm">
#using (Ajax.BeginForm("Edit", "Info", new{id = Model.UserId}, AjaxOptions{OnSuccess = "infoUpdate" }))
{
//FORM FIELDS GO HERE
<input type="submit" value="Save" />
}
</div>
What am I doing wrong that is causing this behavior?
Each time you reload the form, a trigger is placed for submitting the form. Thus you have n submitting, if you reload the form n times.
Try to load the form only once, if it's possible.
You can try to unbind the submit trigger, when you click on your submit button:
<input type="submit" value="Save" onClick="submitForm()" />
var submitForm = function() {
$("#formAddressShipping form").trigger('submit');
$("#formAddressShipping form").unbind('submit');
return false;
};
Just incase someone is still looking for this - the issue can also occur if you have jquery.unobstrusive js referenced multiple times. For me, I had it in layout and partial. The form got submitted 4 times, may be the field count. Removing the js from partial fixed it. Thanks to this thread ASP.NET AJAX.BeginForm sends multiple requests
Moving this jquery.unobtrusive-ajax.js outside partial solved the issue in my case.
I have faced the same issue and solved it as follows. I have a list. From that list, I call New, Update, Delete forms in UI Dialog. Success will close dialog and will return to list and update the UI. Error will show the validation message and dialog will remain the same. The cause is AjaxForm is posting back multiple times in each submit click.
Solution:
//Link click from the list -
$(document).ready(function () {
$("#lnkNewUser").live("click", function (e) {
e.preventDefault();
$('#dialog').empty();
$('#dialog').dialog({
modal: true,
resizable: false,
height: 600,
width: 800,
}).load(this.href, function () {
$('#dialog').dialog('open');
});
});
//Form submit -
$('#frmNewUser').live('submit', function (e) {
e.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $('#frmNewUser').serialize(),
success: function (result)
{
debugger;
if (result == 'success') {
$('#dialog').dialog('close');
$('#dialog').empty();
document.location.assign('#Url.Action("Index", "MyList")');
}
else {
$('#dialog').html(result);
}
}
});
return false;
});
The scripts should be in List UI. Not in partial views (New, Update, Delete)
//Partial View -
#model User
#Scripts.Render("~/bundles/jqueryval")
#using (Html.BeginForm("Create", "Test1", FormMethod.Post, new { id = "frmNewUser", #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.UserID)
<p>#Html.ValidationMessage("errorMsg")</p>
...
}
//Do not use Ajax.BeginForm
//Controller -
[HttpPost]
public ActionResult Create(User user)
{
if (ModelState.IsValid)
{
try
{
user.CreatedDate = DateTime.Now;
user.CreatedBy = User.Identity.Name;
string result = new UserRepository().CreateUser(user);
if (result != "")
{
throw new Exception(result);
}
return Content("succes");
}
catch (Exception ex)
{
ModelState.AddModelError("errorMsg", ex.Message);
}
}
else
{
ModelState.AddModelError("errorMsg", "Validation errors");
}
return PartialView("_Create", user);
}
Hope someone get help from this. Thanks all for contributions.
Credit to http://forums.asp.net/t/1649162.aspx
Move the jQuery scripts inside the DIV. This seemed to fix the problem.
The tradeoff is that every post will do a get for each script.
My first post, faced the same issue
here is the solution which worked for me..
#using (Html.BeginForm("", "", FormMethod.Post, new { enctype = "multipart/form-data", id = "MyForm" }))
{
//form fields here..
//don't add a button of type 'submit', just plain 'button'
<button type="button" class="btn btn-warning" id="btnSave" onClick="submitForm()">Save</button>
<script type="text/javascript">
var submitForm = function () {
if ($("#"MyForm").valid())
{
//pass the data annotation validations...
//call the controller action passing the form data..
handleSaveEvent($("#MyForm").serialize());
}
return false;
};
<script>
}

Categories