how to disable a linkButton in aspx when a certain condition is set - asp.net

Let me explain my problem, I have a LinkButton:
<asp:LinkButton ID="ForceUpdate" runat="server" OnClick="ForceUpdateBtn_Click" Text="<%$ Resources:Resource1, ForceUpdate%>" />
when I click on this LinkButton I set a command and then I check with JQuery if the button is clicked to show a message to wait until the machine is online to get the updated data and then disable the button:
window.setInterval(function () {
$.ajax({
async: true,
type: 'POST',
url: "../../WS/IOT_WebService.asmx/GetUpdateStatusStats",
data: { mccid: <%=mccIdToJavascript%>, language: '<%=currentCulture%>' }, // mccid: ID machine
cache: false,
beforeSend: function () {
},
success: function (txt) {
var string = xmlToString(txt);
string = string.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("<string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("</string>", "");
console.log('check is ', <%=checkClick%>);
var check = <%=checkClick%>;
if (check) {
$('#status-force-update').text(string);
} else {
$('#status-force-update').text('----------');
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}, 3000);
Here's the method from the webservice where I check if in the db a certain data is set (CMD_Date_hour_Ok
!= null) to update the message that the machine is online and enable back the button.
[WebMethod]
public string GetUpdateStatusStats(string mccid, string language)
{
String strResponse = String.Empty;
CultureInfo currentCulture = new CultureInfo(language);
Thread.CurrentThread.CurrentCulture = currentCulture;
Thread.CurrentThread.CurrentUICulture = currentCulture;
try
{
MCC_Machine mcc = MCC_Machine.Retrieve(Convert.ToInt32(mccid));
CMD_Command cmd = CMD_Command.RetrieveByMCCType(mcc, 14); // 14 means that a ForceUpdate were launched
if (cmd == null)
{
cmd = CMD_Command.RetrieveByMCCType(mcc, 14);
}
if (cmd.CMD_Date_hour_Ok != null)
{
// machine is online
strResponse = Resources.Resource1.ForceUpdateStatsOnline.ToString();
}
else
{
// machine is offline
strResponse = Resources.Resource1.ForceUpdateStatsOffline.ToString();
}
}
catch
{
strResponse = Resources.Resource1.ForceUpdateStatsOffline.ToString();
}
return strResponse;
}
Now I need to disable the LinkButton and maybe change the color to grey to get the idea that it is disabled when I click it and enable it when the machine is online.
How can I do that?
Thank you

You need to change disabled attribute of ForceUpdate at every interval as following:
window.setInterval(function () {
$.ajax({
async: true,
type: 'POST',
url: "../../WS/IOT_WebService.asmx/GetUpdateStatusStats",
data: { mccid: <%=mccIdToJavascript%>, language: '<%=currentCulture%>' }, // mccid: ID machine
cache: false,
beforeSend: function () {
},
success: function (txt) {
var string = xmlToString(txt);
string = string.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("<string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("</string>", "");
console.log('check is ', <%=checkClick%>);
var check = <%=checkClick%>;
if (check) {
$('#status-force-update').text(string);
} else {
$('#status-force-update').text('----------');
}
if(string =="Online"){ //check is machine online then set disable false
$("#<%=ForceUpdate.ClientID %>").attr("disabled", false);
}else{ // else mean machine is offline
$("#<%=ForceUpdate.ClientID %>").attr("disabled", true);
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}, 3000);

Related

data table (View) not refreshing after jQuery Ajax call in mvc

I'm facing below issue while refreshing data that has been POSTed using Ajax in MVC. The POST is successfully being executed, but the data on the VIEW does not get refreshed with the new data. When I debug, the values from the Ajax POST are successfully being passed to my controller. When the controller returns the view model return View(objLMT);, my VIEW is not refreshing the new data. How do I get the new data to show in my VIEW?
AJAX
function getAllUserRoleCompany() {
debugger
var url = '#Url.Action("GetAllUserRoleCompany", "UserRoleCompany")';
var Organisation = $("#Organisation").val();
if (Organisation == "All") {
Organisation = "";
}
else {
Organisation = Organisation;
}
var RoleName = $("#RoleName").val();
if (RoleName == "All") {
RoleName = "";
}
else {
RoleName = RoleName;
}
var i = 0;
if ($("#UserName").find("option:selected").length >= 0) {
var len = $("#UserName").find("option:selected").length;
}
else {
len = 0;
}
var UserName = "";
for (; i < len; i++) {
if ($("#UserName").find("option:selected")[i].text != "All") {
if (i == 0) {
UserName = "',";
}
if (i < len - 1) {
UserName += $("#UserName").find("option:selected")[i].text + ",";
UserName = UserName.substring(0, UserName.indexOf("-")) + ",";
}
else {
UserName += $("#UserName").find("option:selected")[i].text + ",'";
UserName = UserName.substring(0, UserName.indexOf("-")) + ",'";
}
}
}
if (UserName == "All") {
UserName = ""
}
else {
UserName = UserName;
}
var UserStatus = $("#UserStatus").val();
if (UserStatus == "All") {
UserStatus = "";
}
else {
UserStatus = UserStatus;
}
$.ajax({
url: url,
data: { Organisation: Organisation, RoleName: RoleName, UserName: UserName, UserStatus: UserStatus },
cache: false,
type: "POST",
success: function (data) {
//$("#dataTables-example").bind("");
//$("#dataTables-example").bind();
//location.reload(true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
Below is the view code on the same page
<div class="row">
#Html.Partial("pv_UserRoleCompany", Model)
Controller
public ActionResult GetAllUserRoleCompany(String Organisation, String RoleName, String UserName, int UserStatus)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
string usrNameWithDomain = System.Web.HttpContext.Current.User.Identity.Name;
//string userID = "261213"; // Environment.UserName;
string userID = "100728";
ViewBag.UserRoleId = objLMTDAL.GetRoleID(userID);
objLMT.TypeList = objLMTDAL.UserRoleCompany_GetAll(Organisation, RoleName, userID, ViewBag.UserRoleId, UserName, UserStatus);
// return Json(objLMT, JsonRequestBehavior.AllowGet);
return PartialView("pv_UserRoleCompany", objLMT);
}
With above code My while SEARCHING or UPDATING view my table/Grid is not refreshing.
Kindly help.
If you are returning a partial view from an AJAX call you have to use jQuery to "refresh" the data.
In your js code you can do this:
$.ajax({
url: url,
data: { Organisation: Organisation, RoleName: RoleName, UserName: UserName,
UserStatus: UserStatus },
cache: false,
type: "POST",
success: function (data) {
//$("#dataTables-example").bind("");
//$("#dataTables-example").bind();
//location.reload(true);
$("#dataTables-example").html(data);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
This will replace the existing HTML with the one from the partial view result in your controller.
#Mihail I have tried using the above solution. It Works I mean it refreshes my view but It's not loading my view perfectly as expected.
View Before (Expected)
View After using $("#dataTables-example").html(data);
Try if this works for you
Call this function as per your call:
function getAllUserRoleCompany(parameters) {
var token = $('[name=__RequestVerificationToken]').val();
$.ajax({
type: "POST",
url: '/UserRoleCompany/GetAllUserRoleCompany',
data: { Organisation: Organisation, RoleName: RoleName, UserName: UserName, UserStatus: UserStatus },
dataType: 'html',
success: function (data) {
$("#").empty().html(data);
}
});
}

How to send image into a specific folder?

I have an input element that selects an image as follows:
HTML Code
<input type="file" id="uploadEditorImage" />
Javascript Code
$("#uploadEditorImage").change(function () {
var data = new FormData();
var files = $("#uploadEditorImage").get(0).files;
if (files.length > 0) {
data.append("HelpSectionImages", files[0]);
}
$.ajax({
url: resolveUrl("~/Admin/HelpSection/AddTextEditorImage/"),
type:"POST",
processData: false,
contentType: false,
data: data,
success: function (response) {
//code after success
},
error: function (er) {
alert(er);
}
});
And Code in MVC controller
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
}
I want to save the selected image in a specific folder such as C\Temp. How can I go about doing that? Please help.
Thank you.
in your html:
<input type="file" id="FileUpload1" />
script:
$(document).ready(function () {
$('#FileUpload1').change(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var data = new FormData();
var files = $("#FileUpload1").get(0).files;
console.log(files);
if (files.length > 0) {
data.append("HelpSectionImages", files[0]);
}
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: data,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
and backend:
[HttpPost]
public ActionResult UploadFiles()
{
// Checking no of files injected in Request object
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Content/"), fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}

Keep login infomation after login in sencha touch 2

I make an small web-application using Sencha touch 2. I have already done with login page. The purpose of second page is get current User session who post Products. This is login page
onSignInCommand: function (view, username, password) {
var me = this;
var loginView = this.getLoginView();
if (username.length == 0 || password.length == 0) {
loginView.showSignInMessage("Please enter your username and password.");
return;
}
loginView.setMasked({
xtype: "loadmask",
message:"Signing in..."
});
//Set ajax
Ext.Ajax.request({
url: "./ajax/Account.ashx",
params: {
type: "login",
username: username,
password: password
},
success: function (response) {
var loginResponse = Ext.JSON.decode(response.responseText);
if (loginResponse.success) {
me.sessionToken = loginResponse.sessionToken;
me.showSignInSuccess();
} else {
me.sessionToken = null;
me.showSignInFailedMessage(loginResponse.message);
}
},
failure: function () {
me.sessionToken = null;
me.showSignInFailedMessage('Login failed. Please try again later.');
}
});
}
And server-side:
private void Login(HttpContext context)
{
var resultStt = "";
var userid = context.Request["username"];
var password = context.Request["password"];
if(!string.IsNullOrEmpty(userid) && !string.IsNullOrEmpty(password))
{
var user = new Select() .From<User>()
.Where("UserID").IsEqualTo(userid)
.And("UserPassword").IsEqualTo(password)
.ExecuteSingle<User>();
if(user!=null)
{
context.Session.Add("PickerUser",user);
resultStt = " {\"success\":true, \"user\":{ \"userId\":"+user.UserID+", \"sessionId\":\"" + context.Session.SessionID + "\"}}";
}
else
{
resultStt = " {\"success\":false, \"message\":\"Login failed. Please enter the correct credentials.\"}";
}
}
context.Response.Write(resultStt);
}
The second page that i need get a list procducts created by user
store: {
autoload:true,
...
proxy: {
type: "ajax",
url: "./ajax/process.ashx?type=loadassigned",
reader:{
type:"json",
rootProperty: "data"
}
}
},
Can not get session because the ajax was loaded at the time of startup app
var currenUser = context.Session["PickerUser"] as User;
You could remove the config:
autoLoad: true
And call this in your login success handler function:
Ext.getStore('yourStoresId').load({
callback: function() {
console.log('my store has loaded');
}
});

Trying to show a value and description in Jquery UI Autocomplete, not showing data, what am I doing wrong?

I have been all over looking to try and solve my issue. I am thinking it may be on my back end but not sure. I am trying to use autocomplete to fill in a textbox but show in the drop down a description with the value.
My Method for grabbing the Data:
[WebMethod]
public static ArrayList GetQueries(string id)
{
queries q;
var cs = Global.CS;
var con = new SqlConnection(cs);
var da = new SqlDataAdapter(querystring, con);
var dt = new DataTable();
da.Fill(dt);
ArrayList rows = new ArrayList(dt.Rows.Count);
for (int i = 0; i < dt.Rows.Count; i++)
{
var val = dt.Rows[i]["Query_ID"];
var des = dt.Rows[i]["Description"];
q = new queries();
q.label = val.ToString();
q.value = val.ToString() + " -- " + des.ToString();
var json = new JavaScriptSerializer().Serialize(q);
rows.Add(json);
}
return rows;
}
public class queries
{
public string label { get; set; }
public string value { get; set; }
}
It is returning an arraylist.
My JQuery Method to get data and autocomplete.
$("[id$=QueryManager]").change(function () {
var id = $("[id$=QueryManager] :selected").val();
$.ajax({
type: 'POST',
url: 'Upload.aspx/GetQueries',
data: JSON.stringify({ id: id }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
fillit(data);
},
error: function (ex) {
alert('Request Status: ' + ex.status + '\n\nStatus Text: ' + ex.statusText + '\n\n' + ex.responseText);
}
});
});
function fillit(data) {
$("#QueryTxt").autocomplete({
delay: 0,
minLength: 0,
source: function (data, response) {
response($.map(data, function (item) {
return {
label: item.label,
value: item.value
}
}));
}
});
};
I have tried it with both the serialize and without to no results. When this code runs it shows that autocomplete is working (via the box showing up below) but there is no data in it.
I am not sure what I am doing wrong, any help is appreciated.
What I'm doing below is that on the "Select" event I take the values returned from the query and set the text of the drop down to the description and Id value from the data brought back. Then I set a dummy textbox's value as the description. "colDescName" is just a variable I was using as my textbox id.
$("#" +colDescName).autocomplete({
minLength: 2,
select: function( event, ui )
{
var rowElement=event.target.id;//Drop down Id
setTimeout(function()
{
$("#"+rowElement).val(ui.item.value+':'+ui.item.id)
},100);//need a slight delay here to set the value
$("#TextBoxId").val(ui.item.value);
//ui.item.value is the description in the drop down.
//ui.item.id is the Id value from the drop down
},
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
lastXhr = $.getJSON("Upload.aspx/GetQueries", request, function (data, status, xhr) {
cache[term] = data;
if (xhr === lastXhr) {
response(data);
}
}).error(function () {
console.log("error");
});
}
});
What object is "$("[id$=QueryManager]")" that you have the change method on? Would you need the change event if you can use the above code?
EDIT
OK an easier way is set your textbox "$("#QueryTxt")" to an autocomplete box before executing any change events on your "QueryManager" manager dropdown. Then when a change event does occur in your "QueryManager" , call:
$(this).autocomplete('search', 'your data here');
That will then execute the search function and call the autocomplete's url with your required data

jquery in visual studio 2012 ultimate and mvc 3

i need to ask something and i am getting stucked of this:
This is my controller code :
public ActionResult FastRegister(FormCollection collection)
{
UserModel db = new UserModel(0);
string str = "";
//Boolean
//Common.IsAlphaNumeric_Dot_Underscore()? er
errorInsert err = new errorInsert();
try
{
db.set_value(0, Common.HtmlFormUrlEncode(collection["user_name"]), Common.HtmlFormUrlEncode(collection["user_pass"]), "", "", Common.HtmlFormUrlEncode(collection["user_email"]), "", DateTime.Now, "", Common.RandomString(false), 0);
db.Insert();
err.duplicate = false;
err.error = "success register";
return Json(err, JsonRequestBehavior.AllowGet);
}
catch (Exception exception)
{
if (exception.Message.Contains("unique") == true && exception.Message.Contains("duplicate") == true)
{
err.duplicate = true;
err.error = "username or email already taken";
}
else
{
err.duplicate = false;
err.error = exception.Message;
}
return Json(err, JsonRequestBehavior.AllowGet);
}
}
}
class errorInsert
{
public Boolean duplicate;
public string error;
public errorInsert()
{
}
}
and this is my jquery code :
<script type="text/javascript">
$(document).ready(function(){
function ajax_send_url(user_name, user_pass, user_email)
{
$.ajax({
type: 'POST',
url: 'http://localhost/smile/User/FastRegister',
data: 'user_name='+user_name+'&user_pass='+user_pass+'&user_email='+user_email,
//contentType: 'application/json; charset=utf-8',
success: function(e)
{
//var x=jQuery.parseJSON(e);
$("#loading").html(e.error);
}
, dataType:"json"
, beforeSend:function (e){$("#loading").html('<img src="loading.gif" width="50px">');}
});
}
$("#register").click
(
function()
{
var user_name = $("#user_name").val();
var user_pass = $("#user_pass").val();
var user_email = $("#user_email").val();
ajax_send_url(user_name,user_pass,user_email );
}
);
});
I've got in my firebug 200 OK Http but no response when i checked. Please someone figure it out and help me. Thanx...

Resources