run method after jquery confimation - c#

How would I run a method in backend to send emails when I have a jquery dialogue with yes and no button as following :
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#dialog").dialog({
autoOpen: false,
modal: true
});
});
$(".confirmLink").click(function (e) {
e.preventDefault();
var targetUrl = $(this).attr("href");
$("#dialog").dialog({
buttons: {
"Yes": function () {
$(this).dialog("close"),
SendEmail(),
window.location.href = targetUrl;
},
"No": function () {
$(this).dialog("close");
}
}
});
$("#dialog").dialog("open");
});
</script>
<a class="confirmLink" href="emailsend.aspx"></a>
<div id="dialog" title="Confirmation Required">
<p>
Do you want to send an email?</p>
</div>

You would have to communicate this with the back end via ajax, the backend would then send the email; a little like this:
function SendEmail(email, content)
{
var data = "email=" + escape(email) + "&content=" + escape(content);
$.ajax({
url: "sendemail.asp",
type: 'POST',
data: data,
success: function(data){
alert("Hurray");
},
error: function() {
alert("Oh noes! It went wrong");
}
});
}

Related

How to call web api in html page using jquery?

I am learning web api where I have created a html page and I want to get <ul> list in my html page.
To call api i have used Jquery ajax call to do so but seems not working. I debugged Jquery but getting no error.
Please suggest me where i am going wrong.
My html code
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="Scripts/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
var listitem = $('#ulEmployees');
$('#btn').click(function () {
debugger;
$.ajax({
Type: 'GET',
url: 'api/employees',
dataType: JSON,
success: function (data) {
listitem.empty();
debugger;
$.each(data, function (index, val) {
var fullname = val.FirstName + ' ' + val.LastName;
listitem.append('<li>' + fullname + '</li>');
});
}
});
});
$('#btnClear').click(function () {
listitem.empty();
});
});
</script>
</head>
<body>
<input id="btn" value="Get All Employees" type="button" />
<input id="btnClear" type="button" value="Clear" />
<ul id="ulEmployees"></ul>
</body>
</html>
Web api GET method
public class EmployeesController : ApiController
{
public HttpResponseMessage Get(string gender="All")
{
using (EmployeeDBEntities entities = new EmployeeDBEntities())
{
switch(gender.ToLower())
{
case "all":
return Request.CreateResponse(HttpStatusCode.OK, entities.Employees.ToList());
case "male":
return Request.CreateResponse(HttpStatusCode.OK, entities.Employees.Where(e => e.Gender.ToLower() == "male").ToList());
case "female":
return Request.CreateResponse(HttpStatusCode.OK, entities.Employees.Where(e => e.Gender.ToLower() == "female").ToList());
default:
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Not found");
}
}
}
}
The datatype should not be passed. Your function should be like below with out datatype as JSON. Internally in jquery the call will fail while it is trying to convert datatype with .toLower function.
$('#btn').click(function () {
debugger;
$.ajax({
Type: 'GET',
url: 'api/employees',
success: function (data) {
listitem.empty();
debugger;
$.each(data, function (index, val) {
var fullname = val.FirstName + ' ' + val.LastName;
listitem.append('<li>' + fullname + '</li>');
});
}
});
});

jQuery UI Autocomplete in MVC modal window

I'm trying to implement the autocomplete jQuery UI function in a Bootstrap modal window, but it does not work.
screenshot module
console debug
Take the steps of not returning a partial view, also already implement jQuery CSS styles, the truth works for me in full views, but why when calling a modal window does not? any help for me?
My Script of where I call the Modal window:
<script type="text/javascript">
$(document).ready(function () {
$("body").on("click", "a.dialog-window", null, function (e) {
e.preventDefault();
var $link = $(this);
var title = $link.text();
$('#AgregarProducto.modal-title').html(title);
var url = $(this).attr('href');
if (url.indexOf('#') == 0) {
$('#AgregarProducto').modal('show');
}
else {
$.get(url, function (data) {
$('#AgregarProducto .te').html(data);
$('#AgregarProducto').modal();
}).success(function () { $('input:text:visible:first').focus(); });
}
});
});
</script>
My Modal Windows:
<div class="form-group">
<div class="col-md-10">
<input type="text" name="producto" id="producto" />
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script>
$(function () {
$("#producto").autocomplete({
source: "/Salidas/BuscarProducto"
});
});
</script>
}
My Controller:
public JsonResult BuscarProducto(string term)
{
using (DataContext db = new DataContext())
{
var resultado = db.Productos.Where(x => x.v_Nombre.Contains(term)).Select(y => y.v_Nombre).Take(5).ToList();
return Json(resultado, JsonRequestBehavior.AllowGet);
}
}
Try to add an event handler for shown.bs.modal before you show the modal itself.
<script type="text/javascript">
$(document).ready(function () {
$("body").on("click", "a.dialog-window", null, function (e) {
e.preventDefault();
var $link = $(this);
var title = $link.text();
$('#AgregarProducto.modal-title').html(title);
var url = $(this).attr('href');
if (url.indexOf('#') == 0) {
$('#AgregarProducto').on('shown.bs.modal', function () {
$("#producto").autocomplete({
source: "/Salidas/BuscarProducto"
});
}
$('#AgregarProducto').modal('show');
}
else {
$.get(url, function (data) {
$('#AgregarProducto .te').html(data);
$('#AgregarProducto').modal();
}).success(function () { $('input:text:visible:first').focus(); });
}
});
});
</script>

Call asp.net function from javascript function

I want to call asp.net function from a javascript function passing string value.
this is the asp.net function :
[System.Web.Services.WebMethod]
public static string InsertData(string ID)
{
string source = "Data Source=(LocalDB)\v11.0;Integrated Security=True;Connect Timeout=30";
using(SqlConnection con = new SqlConnection(source))
{
using (SqlCommand cmd = new SqlCommand("Insert into Book (Name) values(#Name)", con)) {
con.Open();
cmd.Parameters.AddWithValue("#Name", ID);
cmd.ExecuteNonQuery();
return "True";
}
}
}
So i want to call this function from javascript function which passes the string value "ID" to the the asp.net function.
this is the javascript function i use
function CallMethod() {
PageMethods.InsertData("hello", CallSuccess, CallError);
}
function CallSuccess(res) {
alert(res);
}
function CallError() {
alert('Errorrr');
}
and i call it from here
<body>
<header>
</header>
<div class="table" id="div1" > </div>
<form id="Form1" runat="server">
<asp:Button id="b1" Text="Submit" runat="server" onclientclick="CallMethod();return false;"/>
<asp:ScriptManager enablepagemethods="true" id="ScriptManager1" runat="server"></asp:ScriptManager>
</form>
</body>
so i have a button and onClick i want to add "Hello" Row to my table but nothing happens and CallError function calls
You can call web method from ajax call in javascript . you need to set url parameter values to function you want to call and you can pass value in the data prameter in json formate.
like this data:"{ParamterName:'VALUE'}
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "YourPage.aspx/YouPageMethod",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('Method Called Sucess fully');
},
error: function (result) {
alert("error " + result);
}
});
});
</script>
OR
you can call using PageMethod Eample
<script type="text/javascript">
function callInsert() {
PageMethods.InsertDate(id, OnSucceeded, OnFailed);
}
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
}
/* call this javascript function */
callInsert();
</script>
You will need to include Jquery first in your page. Then you need to add the following Javascript code.
<script type="text/javascript">
var id ="5"; //your id will be stored here
$(document).ready(function () {
$.ajax({
type: "POST",
url: "YourPage.aspx/InsertData" + "&?id=" ,
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('Success');
},
error: function (xhr, request, status) {
alert(xhr.responseText);
}
});
});
</script>
You need to have scriptManager in your .aspx page
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
After that you can call the method using
<script type="text/javascript">
function func(){
PageMethods.InsertData(id,success_msg,failure_msg);
}
</script>

How to get jQuery auto-complete "tagify" values in C# ASP.Net

I'm using Tagify, which is basically using jQuery Autocomplete,
references :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script>
<script src="../../../Scripts/jquery.tagify.js" type="text/javascript"></script>
<link href="../../../Styles/jqueryTagify.css" rel="stylesheet" type="text/css" />
Script :
<script>
var myTextArea = $("#txtbox").tagify();
myTextArea.tagify('inputField').autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "Demo.aspx/GetKeyword",
data: "{'match': '" + request.term + "'}",
dataType: "json",
contentType: "application/json",
success: function(data) {
response($.map(data, function(item) {
return {
label: item,
value: item,
}
}));
}
});
},
position: { of: myTextArea.tagify('containerDiv') },
close: function(event, ui) { myTextArea.tagify('add'); },
});
$('form').submit( function() {
var tagStr = $("#txtbox").tagify('serialize');
alert( "Got tags: " + tagStr );
return false;
});
</script>
HTML is :
<input type="text" id="txtbox" />
<input class="submit" type="submit" value="Get Values" />
So when we clicked on submit button, we get tags value from here
var tagStr = $("#txtbox").tagify('serialize');
and when I clicked on getvalues the result like this
How could I get those values in the Code Behind in C#?
add a hidden field in html:
<input id="hiddenTags" name="tags" type="hidden"/>
and update submit js:
$('form').submit( function() {
var tagStr = $("#txtbox").tagify('serialize');
alert( "Got tags: " + tagStr );
$('#hiddenTags').val(tagStr);
return false;
});
now you can get tags in c#:
string tags = Request.Form["tags"];

Jquery Auto complete extender not working after postback

Im using jQuery Autocomplete using Web Service in ASP.Net.I've used the autocomplete to filter employeecode.When the page loads autocomplete works fine,but after when i click the search button autocomplete is not working properly.
I think the problem lies in document.ready function,so when the page loads it works fine,But i've to use autocomplete after the buttonclick event also.
How can i do this ???
Heres my jQuery Autocomplete
<link href="../AutoComplete/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="../AutoComplete/jquery.min.js" type="text/javascript"></script>
<script src="../AutoComplete/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtEmpcode.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/MyWebService.asmx/FetchEmpCode") %>',
data: "{ 'Empcode': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[1],
//val: item
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1
});
});
</script>
Markup
<td align="right">
<asp:Label ID="lblEmpCodeSrch" runat="server" Text="EmpCode" CssClass="label"> </asp:Label>
</td>
<td>
<asp:TextBox ID="txtEmpCodeSrch" runat="server" Width="250px" ToolTip="Enter Employeecode"></asp:TextBox>
<asp:Button ID="bttnSearch" runat="server" CssClass="submit" Height="23px" Text="Search" onclick="bttnSearch_Click" />
</td>
ButtonSearch Codebehind
protected void bttnSearch_Click(object sender, EventArgs e)
{
clsEmp.EMPLOYEEID =txtEmpCodeSrch.Text.Trim()==""? 0:Convert.ToInt32(hFieldEmpId.Value);
DataTable dtEmp = clsEmp.GetDetails();
if (dtEmp.Rows.Count > 0)
{
hFieldEmpId.Value = "";
// txtEmpCodeSrch.Text = "";
if (ViewState["Sort"] != null)
{
DataView dView = new DataView(dtEmp);
dView.Sort = ViewState["Sort"].ToString();
gdView.DataSource = dView;
gdView.DataBind();
}
else
{
gdView.DataSource = dtEmp;
gdView.DataBind();
}
}
}
When you have an UpdatePanel, after the update of the data, you also need to re-initialize the javascript, because the old one is not longer working, because the struct of your html page have change, the dom have change.
The UpdatePanel is giving some function to do that on client side, and your code will be as:
<script type="text/javascript">
// if you use jQuery, you can load them when dom is read.
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
// Place here the first init of the autocomplete
InitAutoCompl();
});
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
// after update occur on UpdatePanel re-init the Autocomplete
InitAutoCompl();
}
function InitAutoCompl() {
$("#<%=txtEmpcode.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/MyWebService.asmx/FetchEmpCode") %>',
data: "{ 'Empcode': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[1],
//val: item
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1
});
}
</script>
I tell you that I could solve the problem by adding a Triggers within the UpdatePanel tag, thus achieves the desired behavior in my case. I hope you can serve you as me helped me.
<ajax:UpdatePanel>
<ContentTemplate>
//My label fire autocomplete
<asp:TextBox id="MyLabelForAutoComplete" runat="server"/>
// Other Html Tags...
<Triggers>
<ajax:PostBackTrigger ControlID="MyLabelForAutoComplete">
</Triggers>
</ajax:UpdatePanel>

Categories

Resources