Display Sweet alert ViewBag Value - javascript

I am developing asp.net core project. Can I Display ViewBag value in sweealert?
Swal.fire({
title: "Successfully Added!",
text: "#ViewBag.OrderNo",
type: "success",
confirmButtonClass: 'btn btn-primary',
buttonsStyling: false,
....
})
Edit

If you want to display the sweet alert after ajax post back. ViewBag does not work like what you want and it is no need.
ViewBag is just an object that gets passed to the view when you render the page. It doesn't make any sense to use that with AJAX; your server-side Razor code runs on initial server render only.
The correct way is to add the data to response data.
Change like below:
<script>
$.ajax({
type: "POST",
url: "/home/AddPurchaseOrder",
contentType: "application/json",
data: JSON.stringify({ "Id": 5, "PurchaseOrderNo": "2342342424" }),
success: function (response) {
Swal.fire({
title: "Successfully Added!",
text: response.orderNo, //change here...
icon: 'success',
confirmButtonClass: 'btn btn-primary',
buttonsStyling: false
})
},
failure: function (response) {
//...
}
});
</script>
Controller:
public class HomeController : Controller
{
[HttpPost]
public JsonResult AddPurchaseOrder([FromBody] PurchaseOrder purchaseOrder)
{
string id = purchaseOrder.Id.ToString();
purchaseOrder.OrderNo = DateTime.Now.ToString("yyyyMMdd") + id;
//ViewBag.OrderNo = purchaseOrder.PurchaseOrderNo;
return Json(new { Id= purchaseOrder.Id , OrderNo= purchaseOrder.PurchaseOrderNo });
}
}

Related

Validation bootstrap 4 with ajax sometimes not passing the data or not working

I tried to validate my form before executing ajax but i ran into some problem, when i tried to validate the data like empty the field the validation is working but sometimes when i submit the data then the ajax is executing the data is not passed and just returned empty string. I dont know why but sometimes its also working. Can you help me check my code ?
ps. i have a video for better understanding the problem, link : https://www.awesomescreenshot.com/video/4998964?key=21785443835131387bfeb191bad975b9
//ajax update product
$('#btn_update').on('click', function() {
var id = $('#idd').val();
var product_name = $('#product_name_edit').val();
var product_price = $('#product_price_edit').val();
$('#edit_product_form').submit(function (event) {
event.preventDefault();
if ($('#edit_product_form')[0].checkValidity() === false) {
event.stopPropagation();
} else {
$("#btn_update").attr("disabled", true).html('Loading ...');
$.ajax({
type: "POST",
url: "<?php echo base_url('admin/edit_product') ?>",
dataType: "JSON",
data: {
id: id,
product_name: product_name,
product_price: product_price,
},
success: function(data) {
$("#btn_update").attr("disabled", false).html('Submit');
$('[name="product_name_edit"]').val("");
$('[name="product_price_edit"]').val("");
$('[name="idd"]').val("");
$('#ModaleditProduct').modal('hide');
Swal.fire({
icon: 'success',
title: 'Data Berhasil di update',
showConfirmButton: false,
timer: 1500
})
window.setTimeout(function() {
location.reload();
}, 2000);
}
});
return false;
}
$('#edit_product_form').addClass('was-validated');
});
});

run ajax call to get form submitting data first, then run the following JavaScript

I have to build a Django web app.
In the frontend, I want to run the ajax call to get the form submitting data first, then run the following JavaScript to process according to the real-time data passed from the backend.
bms/url.py:
path('content_checklist_name_url/', views.content_checklist_name_url, name='content_checklist_name_url'),
view.py:
def content_checklist_name_url(request):
if request.method == 'POST':
try:
Course_Form = ContentChecklistForm(data=request.POST)
if Course_Form.is_valid():
return render(request, 'bms/index.html')
HTML:
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="/static/js/demo/sweetalert2.all.min.js"></script>
function myFunction() {
Swal.fire({
title: '',
text: "Do you want to confirm entries?",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes',
cancelButtonText: 'No'
}).then((result) => {
if (result.value) {
$("#myform").submit();
$.ajax({
url: '/content_checklist_name_url/',
type: 'get',
//async: false,
success: function(data) {
alert(data);
//sleep(500);
if (data.includes('saved'))
{
Swal.fire(
'',
'Entries have been saved.',
'success' )
} else {
Swal.fire(
'',
'Duplicate Entry. This Course Code already exists.',
'error')
}
},
failure: function(data) {
alert('Got an error dude');
}
});
}
else {
window.stop();
}
})
}
But the ajax could not run into at all, some 500 error flashed after form submitting:Failed to load resource: the server responded with a status of 500 (Internal Server Error).
when debug, it runs from the first line of ajax, directly to the last line of ajax.
How could I run ajax to get the data(form submitting result) from the backend first then run the if condition: if (data.includes('saved')) ? So I could do different pop up from the results passed from the backend in real-time.

Passing parameters in Ajax post back in MVC

I am trying to pass ID parameter from a view to a controller on a click delete link available on a selected row.
Simplified View Layout
#using (Html.BeginForm("#", "Schedule", FormMethod.Post, htmlAttributes: new { #class = "floating-labels" }))
{
#Html.AntiForgeryToken()
Delete
}
JavaScript
<script type="text/javascript">
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Schedule", new { id = "id" })',
contentType: "application/json",
data: { id },
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
Controller
namespace Controllers
{
public class ScheduleController
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
//do stuff
}
}
}
But on the click of a delete link I get below error and code does not hit controller action.
I am not able to figure out what mistake I am making...
Here is my locally tested implementation that is working.
ScheduleController class:
public class ScheduleController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Delete(int id)
{
return Ok(id);
}
}
Page that sends the post request:
#Html.AntiForgeryToken()
Delete
<div id="ScheduleList"></div>
<script>
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
var uri = '/Schedule/Delete?id=' + id;
var tokenElement = document.getElementsByName('__RequestVerificationToken')[0];
var data = {
__RequestVerificationToken: tokenElement.value
}
$.ajax({
type: "POST",
url: uri,
data: data,
success: function (result) {
success(result);
}
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
The page does nothing but render the html, and the javascript handles the actual Ajax post. What I believe you were missing is the Validation token in your request.
It is because you are not actullay posting the form pass it correctly and add _token in the ajax data list and value for that token will come from #Html.AntiforgeryToken()
reading the error the request is most probably send correctly and there is an internal server error as mentioned in the 500 respond so please check the code that is inside the controller
Try this, you are accesing a javascript variable on c# code, and you cant do that.
If correct, please mark as answer.
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
var url = '#Url.Action("Delete", "Schedule")?id=' + id;
$.ajax({
type: "POST",
url: url,
contentType: "application/json",
data: { id },
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
I think none of the answers above solve the issue. First of all I would replace your target url:
url: '#Url.Action("Delete", "Schedule", new { id = "id" })',
with
url: '#Url.Action("Delete", "Schedule", new { id = actualIdVariable })',
(replace "id" with the actual id variable from the model you're passing to the view).
Note how your browser response is telling you that the url you're posting to is Schedule/Delete/id. That said, I'm not sure you even need the routeValues in this case (the new { id = ...} parameter). this is a POST action, and action parameters wouldn't come from route unless specified by by attribute routing (i.e. [Route("~/Schedule/Delete/{id}")] attribute on your action).
I think your post action is failing because it is trying to parse the "id" string as an int.
Second, I would change the data property of the ajax call and include the anti forgery token. Just because the anchor element you're binding the click event to, is inside the form with #Html.AntiforgeryToken() doesn't mean the generated token will be posted in the ajax request. You're not actually submitting/posting the form, you're just clicking a button.
it should be something like
data: {
'id': id,
'__RequestVerificationToken': $('[name="__RequestVerificationToken"]').val()
}
try this, it solve the error on routing (different url Action) and the parameter on the controller:
JavaScript
<script type="text/javascript">
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Schedule")',
data: "id=" + id ,
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(string id)
{
//do stuff
}
Nicola.

Cancel button not working in sweetalert

when i am clicking on cancel button in sweetalert.js it still running the AJAX call i want to terminate the process on cancel button.
swal({
title: " Asking price for "+askData[0]+"?",
text: "If you are sure press OK or edit this text",
type: "input",
inputType: "text",
inputValue: "Hello "+askData[1]+", I am interested in buying your "+askData[0]+" of Variety :"+askData[3]+". Please update the Price!",
showCancelButton: true,
closeOnCancelButton:true,
closeOnConfirm: false,
showLoaderOnConfirm: true
}, function(inputValue) {
if (inputValue === "") {
swal.showInputError("Please write something !");
return false;
}
$.ajax({
url: urlEnq,
type: "GET"
});
$.ajax({
url: 'saveUserMessage',
type: "POST",
data: {fieldUserId:fieldUserId,filedUserCompanyId:filedUserCompanyId,message:inputValue},
success: function(data)
{
swal("Done!", "Your message has been successfully sent.", "success");
}
})
.error(function(data) {
swal.showInputError("Please write something !");
});
});
});
});

Webmethod not firing in FlexiGrid

I'm using FlexiGid for my project.But the problem is WebMethod not firing.(Json/Ajax call)
I have put a Debug point to the Webmethod but it's not firing and also Firebug shows the web method Url is correct.
Here i have put the code
Ajax Call
function flexgrid() {
debugger;
$("#flex1").flexigrid({
url: '/WebMethods.aspx/GetIssueSummaryById',
dataType: 'json',
contentType: "application/json; charset=utf-8",
colModel : [
{display: 'ID', name : 'id', width : 40, sortable : true, align: 'center'},
],
data: JSON.stringify({ ProjectId: "1", UserId: "1" }), //Hard code this values at this time
buttons : [
{ name: 'Add', bclass: 'add', onpress: test },
{ name: 'Delete', bclass: 'delete', onpress: test },
{separator: true},
{name: 'A', onpress: sortAlpha},
{name: 'B', onpress: sortAlpha}
],
searchitems : [
{ display: 'Project', name: 'project' },
{display: 'Name', name : 'name', isdefault: true}
],
sortname: "id",
sortorder: "asc",
usepager: true,
title: 'Issue Summary',
useRp: true,
rp: 10,
showTableToggleBtn: true,
width: 1000,
height: 500
});
};
Web Method( thats in WebMethods.aspx file )
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<IssuesVM> GetIssueSummaryById(string UserId, string ProjectId)
{
//Guid LoggedInUserId = new Guid(UserId);
//int ProjectId = Convert.ToInt32(ProjectId);
List<IssuesVM> lst = new List<IssuesVM>();
try
{
SqlCommand comIssueSummary = new SqlCommand("SP_GetIssuesByProjectIDAndOwnerId", conn);
comIssueSummary.CommandType = CommandType.StoredProcedure;
//comIssueSummary.Parameters.Add("#ProjectId", SqlDbType.Int).Value = ProjectId;
// comIssueSummary.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier).Value = LoggedInUserId;
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlDataReader rdr = comIssueSummary.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow r in dt.Rows)
{
//Some code goes here
}
}
catch (Exception)
{
throw;
}
return lst;
}
After that Firebug shows this
Image Here
Can anyone know the Error for this ? Not firing webmethod ?
P.S - I saw some solution in below post[Click Here], I did thatone to the flexigrid.js file but it also not working.
Here is the Change
FlexiGrid.js file (before change )
$.ajax({
type: p.method,
url: p.url,
data: param,
dataType: p.dataType,
success: function (data) {
g.addData(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
try {
if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown);
} catch (e) {}
}
});
},
FlexiGrid.js (After Change )
$.ajax({
contentType: "application/json; charset=utf-8",
data: "{}", // to pass the parameters to WebMethod see below
success: function (data) {
g.addData(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
try {
if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown);
} catch (e) {}
}
});
},
So first off, it might be a good idea to move this to a WebService.asmx file. It is just best and common practice to do so. .ASPX pages respond with HTML/CSS/Javascript normally and .asmx responds with JSON or XML.
Either way, whether the Ajax calls for flexigrid are to a WebService or a Web Forms page, when you add the attribute [WebMethod] to expose a method doing the first Ajax call can be a bit challenging. There is something a bit finicky about Ajax calls to public WebMethods. The finicky arises around the content-type of the request and if the request is JSON or XML and if the response is JSON or XML.
So I am going to show you what I know works for a project I used Flexigrid:
$('#gridTablegSearchProperty').flexigrid({
url: 'Services/WSgSearch.asmx/gridTablegSearchProperty',
colModel: [...
You will notice in the first code snippet I do not set the contentType or the dataType properties of Flexigrid.
And now my WebMethod signature
[WebMethod]
public XmlDocument gridTablegSearchProperty()
{
System.Collections.Specialized.NameValueCollection nvc = HttpContext.Current.Request.Form;
int pgNum = nvc.GetValueAsInteger("page").GetValueOrDefault(1);
int pgSize = nvc.GetValueAsInteger("rp").GetValueOrDefault(20);
string sortName = nvc.GetValueOrDefaultAsString("sortname", "key");
string sortOrder = nvc.GetValueOrDefaultAsString("sortorder", "desc");
string query = nvc.GetValueOrDefaultAsString("query", string.Empty);
string qtype = nvc.GetValueOrDefaultAsString("qtype", string.Empty);
My WebMethod is in a .asmx file, it will not matter if you keep yours in a code behind file but I would move to a WebService and drop the WebMethods.aspx this is poor naming convention and file use convention.

Categories

Resources