I have a autocomplete dropdown which works fine, it however does a postback everytime an item is addded to the list box.
To rectify this I have wrapped the content in an update panel. The autocomplete functions as expected until you click add. Where the postback would usaully be, after the item has been added the autocomplete does not work.
Below is the code:
aspx:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel runat="server" ID="UpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<div class="row">
<div class="span4">
<h3>
Create Season</h3>
</div>
</div>
<div class="row">
<div class="span2">
<label class="control-label" for="TeamName">
Season Name:</label>
</div>
<div class="span3">
<asp:TextBox ID="SeasonNameTextBox" runat="server" Text="Premier League"></asp:TextBox>
</div>
</div>
<div class="row">
<div class="span2">
<label class="control-label" for="TeamName">
Season Year:</label>
</div>
<div class="span3">
<asp:DropDownList ID="DropDownList1" runat="server" Width="100px">
<asp:ListItem>2012/13</asp:ListItem>
<asp:ListItem Value="2013/14">2013/14</asp:ListItem>
<asp:ListItem>2014/15</asp:ListItem>
<asp:ListItem>2015/16</asp:ListItem>
</asp:DropDownList>
</div>
</div>
<div class="row">
<div class="span2">
<label class="control-label" for="TeamName">
Add Team to Season:</label></p>
</div>
<div class="span3">
<asp:TextBox ID="TeamNameTextBox" runat="server" CssClass="searchinput"></asp:TextBox>
</div>
</div>
<div class="row">
<div class="span2">
</div>
<div class="span3">
<p>
<asp:Button ID="AddTeamButton" CssClass="btn btn-primary" runat="server" Text="Add"
OnClick="AddTeamButton_Click" /></p>
</div>
</div>
<div class="row">
<div class="span2">
<label class="control-label" for="TeamName">
Seasons Teams:</label></p>
</div>
<div class="span3">
<asp:ListBox ID="TeamNameListBox" runat="server"></asp:ListBox>
<asp:Button ID="SubmitTeamsButton" CssClass="btn btn-primary" runat="server" Text="Submit"
OnClick="SubmitTeamsButton_Click" />
<asp:Literal ID="TeamCount" runat="server"></asp:Literal>
</div>
</div>
<div class="row">
<div class="span9">
<p>
<asp:Literal ID="CreateSeasonError" runat="server"></asp:Literal></p>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$(".searchinput").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PredictiveSearch.asmx/GetAllPredictions",
data: "{'keywordStartsWith':'" + request.term + "'}",
dataType: "json",
async: true,
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Due to unexpected errors we were unable to load data");
}
});
},
minLength: 1
});
});
</script>
</ContentTemplate>
</asp:UpdatePanel>
asmx:
[System.Web.Script.Services.ScriptService]
public class PredictiveSearch : System.Web.Services.WebService
{
[WebMethod]
public IList<string> GetAllPredictions(string keywordStartsWith)
{
//TODO: implement real search here!
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["RaiseFantasyLeagueConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("[dbo].[findEnglishTeams]", conn);
cmd.CommandType = CommandType.StoredProcedure;
string searchTerm = keywordStartsWith;
SqlParameter searchTermParam = new SqlParameter("#searchterm", searchTerm);
cmd.Parameters.Add(searchTermParam);
IList<string> output = new List<string>();
conn.Open();
SqlDataReader dReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dReader.HasRows)
{
while (dReader.Read())
{
output.Add(dReader["englishTeamName"].ToString());
}
return output;
}
else
{
return output;
}
}
}
Can anyone shed any light on why this might be happening and how to fix it?
Thanks in advance !
Try this:
Use
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded();
for UpdatePanels instead of
$(document).ready() {.. }
Example(not tested):
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(yourAutoCompleteInitializationFunction);
function yourAutoCompleteInitializationFunction() {
$(".searchinput").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PredictiveSearch.asmx/GetAllPredictions",
data: "{'keywordStartsWith':'" + request.term + "'}",
dataType: "json",
async: true,
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Due to unexpected errors we were unable to load data");
}
});
},
minLength: 1
});
}
Related
I am using C# and ASP.NET MVC and try to pass data from the controller to the view. When I debug data show in viewbag but not show in view. The error is undefined. I don't know why this code shows an error.
This is the screenshot:
Screenshot of Debug Result
C# code:
public JsonResult mselectCOACodes(string gl_code)
{
ViewBag.mainCode = gl_code.Substring(0, 2) + "-00-00-0000";
if (ViewBag.mainCode != "")
{
ViewBag.mainDesc = _ICOA.mSelectChartofAccount(ViewBag.mainCode);
}
return Json("", JsonRequestBehavior.AllowGet);
}
jQuery:
<script type="text/javascript">
jQuery(document).ready(function ($) {
$("#txtvglcode").change(function () {
$.ajax({
type: "GET",
url: "/ChartofAccount/mselectCOACodes",
data: {
gl_code: $("#txtvglcode").val()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
View
<div class="col-sm-6">
<div class="col-sm-3">
<div class="form-group">
<b>Main Code</b>
<div class="form-line">
<input type="text" id="txtglmainCode"
value="#ViewBag.mainCode" class="form-control" placeholder="" />
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<b>Description</b>
<div class="form-line">
<input type="text" id="txtmainDescription"
value="#ViewBag.mainDesc" class="form-control" placeholder="" />
</div>
</div>
</div>
</div>
Firstly, don't use #ViewBag to store the input value, because you cannot access its value inside your C# code.
Here is C# code:
public JsonResult mselectCOACodes(string gl_code)
{
string mainCode = gl_code.Substring(0, 2) + "-00-00-0000";
if (mainCode != "")
{
string mainDesc = _ICOA.mSelectChartofAccount(ViewBag.mainCode);
}
return Json(mainDesc, JsonRequestBehavior.AllowGet);
}
Here is JQuery:
<script type="text/javascript">
jQuery(document).ready(function ($) {
$("#txtvglcode").change(function () {
$.ajax({
type: "GET",
url: "/ChartofAccount/mselectCOACodes",
data: {
gl_code: $("#txtvglcode").val()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (mainDesc) {
$("#txtmainDescription").val(mainDesc);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
View:
<div class="col-sm-6">
<div class="col-sm-3">
<div class="form-group">
<b>Main Code</b>
<div class="form-line">
<input type="text" id="txtglmainCode"
value="" class="form-control" placeholder="" />
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<b>Description</b>
<div class="form-line">
<input type="text" id="txtmainDescription"
value="" class="form-control" placeholder="" />
</div>
</div>
</div>
</div>
Here are the details:
Technology: asp.net web forms (c#)
goal: allow user to upload picture and crop it circle
am using cropper.js for this with jquery
Code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="UploadFile" />
</Triggers>
<ContentTemplate>
<div class="container">
<label class="label" data-toggle="tooltip" title="Change your avatar">
<img class="pic-circle" id="imgProfileAvatar" runat="server" alt="avatar" />
<input type="file" class="sr-only" id="input" name="image" accept="image/*" />
</label>
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
</div>
<div class="alert" role="alert"></div>
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel">Crop the image</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="img-container">
<img id="imageToCrop" runat="server" />
<img id="imgCropped" runat="server" />
<asp:Button ID="UploadFile" runat="server" Text="Upload" OnClick="UploadFile_Click" Style="visibility: hidden;"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="crop">Crop</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.bundle.min.js"></script>
<script>
window.addEventListener('DOMContentLoaded', function () {
var avatar = document.getElementById('<%=imgProfileAvatar.ClientID%>');
var image = document.getElementById('<%=imageToCrop.ClientID%>');
var input = document.getElementById('input');
var $progress = $('.progress');
var $progressBar = $('.progress-bar');
var $alert = $('.alert');
var $modal = $('#modal');
var cropper;
$('[data-toggle="tooltip"]').tooltip();
input.addEventListener('change', function (e) {
var files = e.target.files;
var done = function (url) {
input.value = '';
image.src = url;
$alert.hide();
$modal.modal('show');
};
var reader;
var file;
var url;
if (files && files.length > 0) {
file = files[0];
if (URL) {
done(URL.createObjectURL(file));
} else if (FileReader) {
reader = new FileReader();
reader.onload = function (e) {
done(reader.result);
};
reader.readAsDataURL(file);
}
}
});
$modal.on('shown.bs.modal', function () {
cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 3,
});
}).on('hidden.bs.modal', function () {
cropper.destroy();
cropper = null;
});
document.getElementById('crop').addEventListener('click', function () {
var initialAvatarURL;
var canvas;
$modal.modal('hide');
if (cropper) {
canvas = cropper.getCroppedCanvas({
width: 160,
height: 160,
});
initialAvatarURL = avatar.src;
avatar.src = canvas.toDataURL();
$progress.show();
$alert.removeClass('alert-success alert-warning');
//var formData = new FormData();
var data = "{studentIdStr: '<%: this.StudentId %>', imageEncodeString: '" + canvas.toDataURL('image/jpeg') + "'}";
<%--formData.append('avatar', blob);
formData.append('studentIdStr', '<%: this.StudentId %>');--%>
//console.log(JSON.stringify(data));
$.ajax('<%= ResolveUrl("~/Dashboard/Profile.aspx/UploadProfilePic") %>', {
method: 'POST',
data: data,
contentType: "application/json; charset=utf-8",
success: function () {
$alert.show().addClass('alert-success').text('Upload success');
},
error: function () {
avatar.src = initialAvatarURL;
$alert.show().addClass('alert-warning').text('Upload error');
},
complete: function () {
$progress.hide();
},
});
// canvas.toBlob(function (blob) {
//});
}
});
});
</script>
</ContentTemplate>
</asp:UpdatePanel>
Code behind code that gets called when user clicks crop:
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(imageEncodeString);
attachmentDTO.Content = bytes; // sql server data type of varbinary(max)
This works great when I initially select an image and upload it. The cropping is fine too. and so is the saving.
The problem is when I try to redraw the cropped image from database, it does not display anything (default image missing icon). Here is the code on how I am getting the image from database and returning it to UI
var theImage = imageContentRow.Content; //todo:
imgProfileAvatar.Src = "data:image/jpeg;base64," + Convert.ToBase64String(theImage);
and the control where this image is display
<img class="pic-circle" id="imgProfileAvatar" runat="server" alt="avatar" />
What am I missing? Please help!!!
figured it out.
What was happening was
canvas.toDataURL('image/jpeg')
puts the "data:image/jpeg;base64," in the contents. So to fix this what I had to do was replace "data:image/jpeg;base64," with empty string ...aka remove this string...before saving to database.
I have a problem as follow : click button delete , then show modal popup , in modal, i have one button is "OK", when i click button "OK" , process event click of button "OK", such as call action delete via ajax.
my code snippet.
#foreach (var item in Model)
{
<tr>
<td>
#Ajax.ActionLink(" Delete", "", "", new { id = #item.UserProfileID }, new AjaxOptions()
{
HttpMethod = "GET",
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "",
OnSuccess = "ShowModal()"
}, new { #class = "fa fa-times btn btn-danger btn-xs", #id = "bt_del_profile" })
</td>
</tr>
}
<div id="myModal" aria-hidden="true" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-footer">
<button type="button" id="bt_del_ok" class="btn btn-success btn-sm">Ok</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function ShowModal() {
$("#myModal").modal('show');
}
$('#bt_del_ok').click(function (e) {
e.preventDefault();
$.ajax({
url: '/Profile/DelProfile',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
cache: false,
//processData: false,
data: { id: #item.UserProfileID },
success: function (result) {
alert("OK");
},
error: function (result) {
alert("Error delete");
}
});
});
</script>
The problem in here data: { id: #item.UserProfileID }, . I can not get ID in here although when i show devtool chrome , i see <a class="fa fa-times btn btn-danger btn-xs" data-ajax="true" data-ajax-method="GET" data-ajax-success="ShowModal()" href="/Home/Index/P000000002" id="bt_del_profile"> Delete</a>
Can you tell me about this? and give me some advices.
Thank you.
Even though you are using #item.UserProfileID within your java script, it's actually asp.net. If you had this value coming from javascript, you would use it like data: { id: '12345' },
Which means your code should be data: { id: '#item.UserProfileID' }. That should fix your problem.
Some 'Ideas'
You can change your show modal like this.
<div aria-hidden="true" class="modal fade myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-footer">
<button type="button" id="bt_del_ok" class="btn btn-success btn-sm">Ok</button>
</div>
</div>
</div>
Then change your ShowModal like below.
function ShowModal(userProfileId) {
$(".myModal").prop('id', userProfileId);
$(".myModal").modal('show');
}
Then in delete event;
var userProfileId = $(".myModal").prop('id');
data: { id:userProfileId },
Here is the acsx page.
I have two drop down in Bootstrap modal (State and City).
Based on the state selection, City dropdown should populate option.
I have created two methods in code behind for state FillStatedata() and for city getCitydata().
I need to call getCitydata() method on state selection change using jQuery AJAX and then bind the city data with city drop down.
I am getting Statename on state change but not able to executive getCitydata() method using statename as parameter.
Why?
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Registeration.ascx.cs" Inherits="WebApplication1.UserControl.Registeration" %>
<%# Import Namespace = "System.Web.Security" %>
<script src="~/scripts/jquery-1.10.2.js"></script>
<script src="~/scripts/jquery-1.10.2.min.js"></script>
<!--jquery start here-->
<script>
$(document).ready(function () {
var getSelState;
$("#State").change(function () {
$.ajax({
type: "POST", //HTTP method
url: "UserControl/Registeration.ascx/getCitydata", //page/method name
data: alert("{'Statename':'" + $('#State').val() + "'}"), //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) { //handle the callback to handle response
//request was successful. so Retrieve the values in the response.
}
})
});
});
</script>
<input type="hidden" id="myhiddenField" name="myhiddenField" value="" ClientIDMode="Static" runat="server" />
<div class="form-horizontal" role="form" runat="server">
New User?
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Register</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="full-name" class="col-sm-2 control-label">FullName:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="full-name">
</div>
</div>
<div class="form-group">
<label for="User-Name" class="col-sm-2 control-label">Username:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="User-Name">
</div>
</div>
<div class="form-group">
<label for="Create-Password" class="col-sm-2 control-label">Create Password:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Create-Password">
</div>
</div>
<div class="form-group">
<label for="confirm-Password" class="col-sm-2 control-label">Confirm Password:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Confirm-Password">
</div>
</div>
<div class="form-group">
<label for="Mobile-Number" class="col-sm-2 control-label">Mobile No:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Mobile-Number">
</div>
</div>
<div class="form-group">
<label for="State" class="col-sm-2 control-label">State:</label>
<div class="col-sm-10">
<select class="form-control" id="State" runat="server" ClientIDMode="Static">
</select>
</div>
</div>
<div class="form-group">
<label for="City" class="col-sm-2 control-label">City:</label>
<div class="col-lg-10">
<select class="form-control" id="City" runat="server" DataTextField="Cityname"
DataValueField="Cityname"></select>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<button type="button" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-primary">Cancel</button>
</div>
</div>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
First things first.
just use one library either min for prod or non min for dev.
data:{} should have to be an object or string value.
use one of it:
<script src="~/scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
var getSelState;
$("#State").change(function() {
$.ajax({
type: "POST", //HTTP method
url: "UserControl/Registeration.ascx/getCitydata", //page/method name
data: "{'Statename':'" + this.value + "'}", //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) { //handle the callback to handle response
console.log(msg);
}
});
});
});
</script>
function getCitydata()(obj) {
var ddlcity = document.getElementById('<%= ddlcity.ClientID %>');
ddlcity.innerHTML = '';
$.support.cors = true;
var serviceUrl = '/ashx/map/Address.ashx';
if (serviceUrl.indexOf('?') > -1)
serviceUrl += '&jsonp='
else
serviceUrl += '?jsonp='
serviceUrl += '?&type=1&StateId=';
serviceUrl += document.getElementById('<%= ddlState.ClientID%>').value;
$.ajax({
type: 'GET',
crossDomain: true,
async: false,
contentType: 'application/json; charset = utf-8',
url: serviceUrl,
data: '{}',
dataType: 'jsonp',
success: function (data) {
if (data != null && data.length > 0) {
$.map(data, function (item, index) {
var newListItem = document.createElement('option');
newListItem.text = item.City;
newListItem.value = item.CityId;
ddlcity.options.add(newListItem);
});
}
},
error: function (error) {
alert('error ' + error);
}
});
} // getCitydata()
To use this function you have to create one ashx file eg. Address.ashx file which consist method for getting the data from database
When i click into the Button which is placed inside a usercontrol, i dont get the values that are inputted into the textbox on the button click event. please suggest any alternate.
my UserControl Markup:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="SearchPopup.ascx.cs"
Inherits="trg.dgs.sites.web.ui.ui.charternew.usercontrol.SearchPopup" %>
<script type="text/javascript">
// function searchPopuptester() {
// debugger;
// var address = document.getElementById('<%= txtAddress.ClientID %>').value;
// //alert(address);
// var zip = document.getElementById('<%= txtZip.ClientID %>').value;
// // alert(zip);
// var aptnum = document.getElementById('<%= txtSuite.ClientID %>').value;
// alert(aptnum);
// debugger;
// $.ajax({
// type: "GET",
// url: "ui/charternew/usercontrol/SearchPopup.ascx/SearchAddress",
// data: [{ address: address, suite: aptnum, zip: zip}],
// datatype: "json",
// success: function (data) {
// window.location = data.d;
// },
// failure: function () {
// alert("Sorry,there is a error!");
// }
// });
// }
</script>
<div class="form_wrapper">
<div class="formarea">
<div class="form_heading">
<h4>
Check Service Availability</h4>
<p>
TO FIND THE BEST DEALS IN YOUR AREA</p>
</div>
dddddddddddd
<p>
<img src="ui/charternew/images/lock_icon.png" alt="Lock Icon" class="lock_icon" />Your
Information is Private and Secure</p>
<div class="feild_set">
<div class="feild_bar">
<asp:TextBox ID="txtAddress" runat="server" MaxLength="30" CssClass="feild1" />
</div>
<div class="feild_bar">
<div class="apt_feild">
<asp:TextBox ID="txtSuite" runat="server" MaxLength="25" CssClass="feild2" />
</div>
<div class="zipcode_feild">
<asp:TextBox ID="txtZip" runat="server" MaxLength="5" CssClass="feild2" />
</div>
</div>
<div class="feild_bar">
<asp:CheckBox ID="Ismoving" CssClass="tflables" TextAlign="right" runat="server"
Checked="false" />
<label>
Moving?</label>
<label id="lblMoveDate" style="display: none;">
<asp:TextBox ID="txtmovedate" runat="server" CssClass="txtfield" MaxLength="50" />
</label>
</div>
<asp:LinkButton ID="btnSubmit" runat="server" CssClass="btn" OnClick="btnSubmit_Click">Find My BEST Deals</asp:LinkButton>
</div>
<!-- End Form -->
</div>
</div>
My UserControl Code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string add = txtAddress.Text; }