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);
}
});
}
Related
when i pass data to the first action its working fine and based on the return of that action i call another one with another ajax post request and pass the same data but the error message appears on console and nothing happens, note that if i don't pass data at all(not in the same nor the second query) both actions get called without problem but with no data passed enter image description here
those are the codes for the actions and the script(second)
[HttpPost]
public async Task<bool> Check(string login = "", string password = "")
{
var model = new HomeViewModel()
{
LoginRequest = new LoginRequest()
{
Login = login,
Password = password,
}
};
var test = model;
var authResult = await _accountUseCases.LoginAsync(model).ConfigureAwait(false);
var testAuthResult = authResult;
return authResult.force;
}
[HttpPost]
public async Task<IActionResult> LoginV2(string login = "", string password = "")
{
var model = new HomeViewModel()
{
LoginRequest = new LoginRequest()
{
Login = login,
Password = password,
}
};
var test = model;
var authResult = await _accountUseCases.LoginAsync(model).ConfigureAwait(false);
if (!authResult.result)
{
model.LoginRequest.Password = "";
TempData["Message"] = authResult.message;
return RedirectToAction("Index", "Login", model);
}
if (!string.IsNullOrEmpty(model.ReturnUrl) && Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
return RedirectToAction("Index", "Trainings");
}
public IActionResult IndexV2()
{
return View();
}
and this is the script
#using System.Text.Encodings.Web
#using Microsoft.AspNetCore.Mvc.Localization
#using Microsoft.Extensions.Localization
#using UI
#inject IViewLocalizer Localizer
#inject IStringLocalizer<SharedResource> SharedLocalizer
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
#functions {
private string GetAntiXsrfRequestToken()
{
return Xsrf.GetAndStoreTokens(Context).RequestToken;
}
}
<script type="text/javascript" nonce="bGFsYWNvY29qYW1ib2xhbGF5ZWFhYWE=">
$(document).on("click", "#LoginFormSubmit",
function (e) {
setLoginCredentials();
})
function GetLoginCredentials() {
var login = document.getElementById("txtUsername2").value;
var pwd = document.getElementById("Password").value;
var data = {
'login': login,
'password': pwd
};
//var jData = JSON.stringify({ login: login, password: pwd });
//return jData
return data ;
}
function setLoginCredentials() {
var data = GetLoginCredentials();
console.log(data);
$.ajax({
type: "POST",
url: "#Url.Action("Check", "Login")",
headers: {
"RequestVerificationToken": "#GetAntiXsrfRequestToken()"
},
//contentType: "application/json; charset=utf-8",
//dataType: "json",
//data: JSON.stringify({login:data.login, password: data.password}),
data: data,
success: function (result, status, xhr) {
if (result == true) {
$('#LoginConfirmationModal').modal('show');
}
else if(result == false) {
//var data2 = GetLoginCredentials();
$.ajax({
type: "POST",
url: "#Url.Action("LoginV2", "Login")",
headers: {
"RequestVerificationToken": "#GetAntiXsrfRequestToken()"
},
data: data,
//contentType: "application/json",
//dataType: "json",
//data: JSON.stringify({ login: data.login, password: data.password }),
//data:JSON.stringify({login:data2.login , password:data2.password}),
//contentType:"application/json;charset=utf-8",
//dataType:"json",
success: function (result, status, xhr) {
},
error: function (xhr, status, error) {
}
});
}
}
,
error: function (xhr, status, error) {
}
});
};
</script>
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);
I have a linq query in my controller that returns values from the database in JSON format. However The JSON object has no name so I tried a couple things but everything returns undefined.
My JSON object looks like:
Object {UserId: 4, UserName: "John", UserPassword: "Password"}
Controller
[HttpPost]
public JsonResult Index(string searchString, string searchPassword)
{
var user = (from u in db.Users where u.UserName.Equals(searchString) && u.UserPassword.Equals(searchPassword) select u).FirstOrDefault();
return Json(user);
}
Ajax
$('#test2').click(function(e) {
e.preventDefault();
var user = "John";
var userpass = "Password";
$.ajax({
url: "#Url.Action("Index", "Users")",
data: { "searchString": user, "searchPassword": userpass },
type: "post",
success: function (data) {
var results = [];
for (var i = 0; i < data.length; i++) {
results[data[i]["Key"]] = data[i]["Value"];
}
alert((result.UserName));
alert((result.UserPassword));
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr, ajaxOptions, thrownError);
}
})
})
The alerts come up with just undefined
You should be able to access the object by just using the properties from your C# object. So in your ajax success function, just use data.UserId or data.UserName
Do this in your ajax success
success: function (data) {
var results = [];
for (var i = 0; i < data.length; i++) {
result.push(data[i].UserId +" "+ data[i].UserName);
}
alert(result);
}
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');
}
});
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...