Datalist Delete Command Event implementation using Page Methods - javascript

I have a DataList and Update Panel in my page. After implementation, I checked that the response is talking very long time after using Update panels...Here is the study material. I have a Delete Command event in Datalist and works find in the above mentioned case. I was trying to implement Delete Command using Page Methods. Any Idea how to do that?
I basically want to find hidden controls in this event and have to delete the record in `database. Any help will be highly appreciated.

Rest Services
The full application can be downloaded from:
http://sdrv.ms/LJJz1K
This sample uses rest services in ASP.Net (the same concepts can be applied to a MVC application)
The clearer advantage when using rest services vs page methods, is testability.
I will guide you step by step to configure the service:
You need the following references:
System.Web.ServiceModel.dll
System.Web.ServiceModel.Activation.dll
System.Web.ServiceModel.Web.dll
Nuget packages:
jQuery
jQuery plugins:
jQuery Block UI (it’s available as a single script file)
Service info
[ServiceContract]
public interface IMyService
{
[OperationContract]
[WebInvoke(
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "/DeleteFromService",
Method = "DELETE")]
void Delete(int id);
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService
{
public void Delete(int id)
{
// delete your product
// simulate a long process
Thread.Sleep(5000);
}
}
In Global.asax
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}");
RouteTable.Routes.Add(new ServiceRoute("",
new WebServiceHostFactory(),
typeof(MyService)));
}
In web.config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true"
automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
Register scripts (they can be registered in a master page)
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js" language="javascript" ></script>
<script language="javascript" type="text/javascript" src="Scripts/jquery.blockui.1.33.js"></script>
In a ASP.Net content page (in this sample, I am using a master page)
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<input type="button" value="Delete" id="myButton" />
</asp:Content>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript" language="javascript">
function deleteFromService() {
if (!confirm("Are you sure you want to delete?")) {
return;
}
$.blockUI();
$.ajax({
cache: false,
type: "DELETE",
async: true,
url: "/DeleteFromService",
data: "3", // get your id to delete
contentType: "application/json",
dataType: "json",
success: function () {
$(document).ajaxStop($.unblockUI);
alert("done");
},
error: function (xhr) {
$(document).ajaxStop($.unblockUI);
alert(xhr.responseText);
}
});
}
jQuery().ready(function () {
$("#myButton").click(deleteFromService);
});
</script>
</asp:Content>
And that’s it, ajax commands the easy way =)

Related

tags input with typeahead from server local data source

I want to synthesize a Json array of objects for the auto complete from server side, and for now I hard coded something like below when page loads but it didn't work. However when I changed it like "local: [{ name: 'Foo' }, { name: 'FFoo' }, { name: 'Ah' }]" in JS file, it works.
Is it possible to render the "local" data from server side and how can I make a Json string using Vb.net?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
hdTypeahead.Value = "[ { 'name': 'ah'},{ 'name': 'ba'},{ 'name': 'cha'} ]"
End Sub
var dataSetBloodhound = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
//local: $('#<%= hdTypeahead.ClientID %>').val()
local: [{ name: 'Foo' }, { name: 'FFoo' }, { name: 'Ah' }]
});
dataSetBloodhound.initialize();
$('input').tagsinput({
freeInput: true,
typeaheadjs: {
name: 'dataSetBloodhound',
displayKey: 'name',
valueKey: 'name',
source: dataSetBloodhound.ttAdapter()
}
});
<link href="https://rawgit.com/timschlechter/bootstrap-tagsinput/master/src/bootstrap-tagsinput.css" rel="stylesheet"/>
<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<script src="http://bootstrap-tagsinput.github.io/bootstrap-tagsinput/dist/bootstrap-tagsinput.min.js"></script>
<input type="text" value="Amsterdam,Washington,Sydney,Beijing,Cairo" data-role="tagsinput" />
<input runat="server" id="hdTypeahead" type="text" value="" style="display:none"/>
try
local: JSON.parse($('#<%= hdTypeahead.ClientID %>').val())
or please open console log to the same page and get exact value of this element from $('#<%= hdTypeahead.ClientID %>')
The problem is not with your data coming from server side it is actually parsing of java script array to a variable. Your data is stored in string format in hdTypeahead control's val, so in order to make it an array you have to use some parser present in java script. I have implemented the code as follows:
WebForm1.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="tempApp2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<input id="hidTypeAhead" type="hidden" runat="server" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var typeAhead = JSON.parse($('#<%= hidTypeAhead.ClientID %>').val());
console.log(typeAhead.data);
</script>
</body>
</html>
WebForm1.aspx.vb
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace tempApp2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
hidTypeAhead.Value = #"{""data"":[{ ""name"": ""Foo"" }, { ""name"": ""FFoo"" }, { ""name"": ""Ah"" }]}";
}
}
}
So first understand that you have array data in string not some object while JS have JSON.parse() method which can parse string to JS object. So you simply have to add your array to an object within the string as I have done as follows:
hidTypeAhead.Value = #"{""data"":[{ ""name"": ""Foo"" }, { ""name"": ""FFoo"" }, { ""name"": ""Ah"" }]}";
I have added my array in data property of the JS object. The next part is to parse it using JSON.parse() the following code will do the needy:
var typeAhead = JSON.parse($('#<%= hidTypeAhead.ClientID %>').val());
So that's it you will get your array in typeAhead variable's "data" property which you can then assign to your property "local" as
local: typeAhead.data
Or directly
local: JSON.parse($('#<%= hidTypeAhead.ClientID %>').val()).data;
Hope it helps

Not getting a callback with Ajax.BeginForm asp.net mvc

I am unable to hit the server code using Ajax.BeginForm()
Here is part of my View where I used the Ajax Helper method
#model Ride.MMReports.ViewModels.ManualRecViewModel
.....
var options = new AjaxOptions
{
OnBegin = "OnBeginMethod",
OnFailure = "OnFailureMethod",
OnSuccess = "OnSuccessMethod",
OnComplete = "OnCompleteMethod",
HttpMethod = "Post"
};
using (Ajax.BeginForm("Index", "ManRecReport", options))
{
<button type="submit"
name="action"
value="Export to excel"
id="export-excel"
class="btn btn-primary"
Export to excel
</button>
}
#section scripts
{
#Scripts.Render("~/bundles/report")
#Scripts.Render("~/bundles/jqueryval")
}
My bundle include jquery.unobtrusive-ajax.js and also reports.js where I have all the event methods
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
reports.js bellow. The browser is able to show the alert but last method it calls is OnFailureMethod
var isError = false;
function OnBeginMethod() {
alert("OnBeginMethod");
}
function OnFailureMethod(error) {
isError = true;
alert("OnFailure");
}
function OnSuccessMethod(data) {
alert("OnSuccess");
}
function OnCompleteMethod(data, status) {
if (!isError) {
alert("OnCompleteMethod");
}
}
The problem here is when I click the button, jquery-3.1.1.js is failing
http://localhost:31111/[object%20HTMLButtonElement] 404 (Not Found)
failing at this line
xhr.send( options.hasContent && options.data || null );
My Controller method looks like this:
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Index(ManualRecViewModel vm)
{
....
}
Any thoughts what I am doing wrong?

Can we get data in aspx.cs page from Angular controller?

I have a project which contains all plain html pages with angularJS and one .aspx page. I need some data in list/json format in my aspx page's code behind from angular controller. Can this be done ? If yes, please guide.
I'm new to angular, please be kind.
Scenario is I want to download the current html page as pdf. I found jspdf but for some reason it is not working in IE, works in chrome.
So, I am putting a workaround where I can do this with aspx page, I just need data there.
//Download PDF
$scope.PDFDownload = function () {
window.open('ReportPage.aspx');
//need to send list/json data to aspx code behind here.
}
I need some data in list/json format in my aspx page's code behind
from angular controller.
If you want to send/receive data to/from ASPX Web Form, you want to use WebMethod.
using System.Web.Script.Serialization;
namespace DemoWebForm
{
public partial class Default : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string PostJson(string firstName, string lastName)
{
return new JavaScriptSerializer().Serialize(
"Hello, " + lastName + ", " + firstName + "!");
}
}
}
Usage
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWebForm.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body ng-app="demoApp">
<form id="form1" runat="server" ng-controller="DemoController">
<pre>{{user}}</pre>
<button type="button" onclick="ajaxPostData();">Post Data Ajax</button>
<button type="button" ng-click="ngPostData()">Post Data Angular</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript">
function ajaxPostData() {
var user = { firstName: "John", lastName: "Doe" };
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/default.aspx/postjson") %>',
data: JSON.stringify(user),
contentType: "application/json",
success: function (msg) {
console.log(msg.d);
}
});
}
var demoApp = angular.module('demoApp', [])
.controller('DemoController', function DemoController($scope, $http) {
$scope.user = { "firstName": "John", "lastName": "Doe" };
$scope.ngPostData = function () {
$http.post('<%= ResolveUrl("~/default.aspx/postjson") %>', $scope.user)
.then(function (result) {
console.log(result.data.d);
});
}
});
</script>
</form>
</body>
</html>
Screen shot

Controller function call twice in asp.net mvc

When I click the save button to save my controller function is firing twice. What is the problem in my code I don't know. Please help me.
Here is my button click to call ajax and save values.
<button id="btnSave" type="submit" title="Save" class="btn btn-success" onclick="getPage('#(Url.Action("Save", "Carriers"))')">
<span class="glyphicon glyphicon-floppy-disk"></span>Save
</button>
Here is my ajax
$.ajax({
type: "POST",
url: page,
data: $("#frmEdit").serialize(),
xhrFields: {
withCredentials: true
},
success: function (html) {
$('#CarrierList').empty();
$('#CarrierList').append($.parseHTML(html));
},
error: function () {
var error = "Error occured during loading Carrier items...";
$('#errorMessage').empty();
$('#errorMessage').append(error);
$('#errorModal').modal('show');
},
complete: function () {
$('#loaderImg').modal('hide');
}
});
}
Here is my controller method
public override ActionResult Save(CarrierDTO carrierDTO)
{
string[] ErrorMessageArray = new string[4];
int errorIndex = 0;
if (ModelState.IsValid)
{
MessageCollection messages = new MessageCollection();
carrierDTO.Save(ref messages);
if (messages.IsErrorOccured() || messages.IsExceptionOccured())
{
ModelState.AddModelError("", messages[0].Text);
return View("Edit", carrierDTO);
}
return View("Edit", carrierDTO);
}
You need to add 'preventDefault()'.
If the prevent default method is called, the default action of the event will not be
triggered.
In your case, the prevent default will stop submitting the form(the default action of the submit button), and use the ajax snippet to do so instead.
JQ:
$(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: page,
data: $("#frmEdit").serialize(),
xhrFields: {
withCredentials: true
},
success: function (html) {
$('#CarrierList').empty();
$('#CarrierList').append($.parseHTML(html));
},
error: function () {
var error = "Error occured during loading Carrier items...";
$('#errorMessage').empty();
$('#errorMessage').append(error);
$('#errorModal').modal('show');
},
complete: function () {
$('#loaderImg').modal('hide');
}
});
}
});
Two solutions
Use type="button" in your button control
<button id="btnSave" type="button" title="Save" class="btn btn-success" onclick="getPage('#(Url.Action("Save", "Carriers"))')">
<span class="glyphicon glyphicon-floppy-disk"></span>Save
</button>
or remove onclick="getPage('#(Url.Action("Save", "Carriers"))'), because the submit button take a post action in default .
<button id="btnSave" type="submit" title="Save" class="btn btn-success" ">
<span class="glyphicon glyphicon-floppy-disk"></span>Save
</button>
In you App_Start folder open the BudleConfig.cs file and do few changes:
First take a look to this line (this is an original VS generated content).
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
Note that '...validate*' pattern will load five scripts from your Scripts folder (this is true for my case):
~/Scripts/jquery.validate-vsdoc.js
~/Scripts/jquery.validate.js
~/Scripts/jquery.validate.min.js
~/Scripts/jquery.validate.unobtrusive.js
~/Scripts/jquery.validate.unobtrusive.min.js
As you can see, you are loading the unobtrusive.js twice (jquery.validate.unobtrusive.js and jquery.validate.unobtrusive.min.js). So, make your own code something like this to exclude, say full version js:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate-vsdoc.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate.min.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate.unobtrusive.min.js"));
or make some mechanism to load full or min versions per your desire.

Implementing Ajax in spring MVC

Ajax is not sending the data to the specified URL. Here is my controller:
#Controller
public class HomeController {
private List<User> userList = new ArrayList<User>();
#RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)
public String showForm() {
return "AddUsers";
}
#RequestMapping(value = "User.htm", method = RequestMethod.POST)
public #ResponseBody
String addUser(#ModelAttribute(value = "user") User user,
BindingResult result) {
String returnText;
if (!result.hasErrors()) {
userList.add(user);
returnText = "User has been added to the list. Total number of users are"
+ userList.size();
} else {
returnText = "Sorry, an error has occur. User has not been added to list.";
}
return returnText;
}
#RequestMapping(value = "ShowUsers.htm")
public String showUsers(ModelMap model) {
model.addAttribute("Users", userList);
return "ShowUsers";
}
}
AddUser.jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<script src="/AjaxWithSpringMVC2Annotations/js/jquery.js"></script>
<script type="text/javascript">
function AjaxCall() {
alert('ready');
//get the form variables....
var name = $('#name').val();
var education = $('#education').val();
$.ajax({
type: "POST",
url: "AddUsers.htm",
data: " name=" + name + "&education=" + education,
success: function (response) {
$('#info').html(response);
$('#name').val('');
$('#education').val('');
},
error: function (e) {
alert('ERROR : ' + e);
}
});
}
</script>
<body>
<h1>Welcome to the AddUsers page. </h1>
<table>
<tr><td>Enter your name : </td><td> <input type = "text" id="name"></td></tr>
<tr><td>Educational qualification : </td><td> <input type = "text" id="education"></td></tr>
<tr><td colspan = "2"><input type="button" value="Add Users" onclick="AjaxCall()"></td></tr>
<tr><td colspan = "2"><div id ="info"></div></td></tr>
</table>
Show users
</body>
</html>
I have inserted an alert within the ajax which never comes up. So I believe there is something wrong with the ajax method.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I have also created a domain class which would store the student information:
public class User {
private String name = null;
private String education = null;
public void SetName(String name) {
this.name = name;
}
public String GetName() {
return name;
}
public void SetEdu(String education) {
this.education = education;
}
public String GetEdu() {
return education;
}
}
There is also a warning:
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with
URI [/sum/] in DispatcherServlet with name 'appServlet'>`
Dispatch servlet:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources
in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-
INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.faisal.sum" />
</beans:beans>
I corrected the upper case problem ($.ajax instead of $.Ajax). Thanks for pointing out.
Now I have a different error:
POST http://localhost:8080/sum/AddUsers.htm 405 (Method Not Allowed)
change url:"AddUsers.htm" to url: "${pageContext. request. contextPath}/AddUsers.htm" and try.
the url you are calling is this
type: "POST",
url: "AddUsers.htm",
Which is POST, the controller method is GET. Hecne the 405 error, method not supported.
You try to send POST request but mapped your method call with GET method
#RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)
try to change RequestMethod.GET to POST

Categories