Access string stored in a ViewBag on ajax success - javascript

I'm pretty new to ASP.NET MVC, I been searching for a solution for this problem but I couldn't find any proper solution. I found some solutions here on stachoverflow but nothing has worked with me. Here are some links:
Possible to access MVC ViewBag object from Javascript file?
MVC 3 - Assign ViewBag Contents to Javascript string
Here is my ajax call to the server:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Prize/UploadPassport');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText)
if (data.nationality != "") {
$('#PassportData tbody').append('<tr><td data-title="#Web.Resources.MyResources.PassportNationality">' + data.nationality + '</td><td data-title="#Web.Resources.MyResources.PassportName">' + data.passportName + '</td><td><a><i id="viewApp_' + data.passportID + '" class="fa fa-search fa-lg" onclick="ViewPassport(' + data.passportID + ');"> <iframe id="img_' + data.passportID + '" class="costumeiframe"></iframe></i></a></td></tr>');
}
else {
//var errorMsg = data.errorMsg;
ShowDataValidationMessage("#ViewBag.FileError"); //here i'm getting an empty string
}
}
}
In my server side action I set ViewBag.FileError based on some conditions here it is:
public ActionResult UploadPassport(HttpPostedFileBase FileUpload, string PassportCopyNationality)
{
if (Condition)
{
//Database access
}
else
{
if (isFileAlreadyExist)
{
ViewBag.FileError = Web.Resources.MyResources.PassportAttachmentValidationForFile;
}
else if (file.ContentLength > 3145728 || !isFileTypeLegal)
{
ViewBag.FileError = Web.Resources.MyResources.FileError;
}
return Json(new { nationality = "", passportName = "", passportID = "" });
}
}
catch (IOException io)
{
return Json("File not uploaded");
}
}
The problem that I'm getting an empty string

Firstly, #ViewBag.FileError (inside your script) is razor code which is parsed on the server before your view is sent to the client, so unless you include ViewBag.FileError = someValue in the GET method that generates this view, then it will always equate to null.
Secondly, your UploadPassport() method is returning a JsonResult not a view, so ViewBag does not even exist. You can resolve this by adding the value to the JsonResult, for example
return Json(new { fileError = someValue, nationality = "", passportName = "", passportID = "" });
and then access it in the script
ShowDataValidationMessage("data.fileError");

Related

Why is the Ajax call not being hit?

I am trying to apply a filter to data that is being displayed on a map but for some reason, the Ajax call that I have set up is not being executed. I can reach the console.log line in the view but anything after that in the Ajax call is never executed. This is being done in ASP.NET MVC.
I have similar Ajax calls in this project from other developers that function in a similar manner. I have tried to restructure my code to work in a similar manner, but with no success. The other developers have no idea what is going on either.
C# in the controller
[HttpPost]
public ActionResult MapFilter(string filterLake, bool filterPets)
{
var filteredProperties = db.Properties.Include(a => a.PropertyCategory).Where(b => b.Status == true).Select(x => new { x.PropertyName, x.PropertyId, x.RatePerNight, x.RatePerWeek, x.MarketingTitle, x.Latitude, x.Longitude, x.Pets, x.PropertyCategory.PropertyCategoryName });
if (filterLake != "")
filteredProperties = filteredProperties.Where(a => a.PropertyCategoryName == filterLake);
if (filterPets != true)
filteredProperties = filteredProperties.Where(a => a.Pets == filterPets);
var jsonProperties = JsonConvert.SerializeObject(filteredProperties);
return new JsonResult()
{
Data = jsonProperties,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
JavaScript & Ajax in the View
var filterLake, filterPets;
var btnApplyFilters = document.getElementById("applyFilters");
var filterLakeNode = document.getElementById("filterLake");
var filterPetsNode = document.getElementById("filterPets");
$(document).ready(function () {
btnApplyFilters.onclick = function () {
filterLake = filterLakeNode.options[filterLakeNode.selectedIndex].value;
filterPets = filterPetsNode.options[filterPetsNode.selectedIndex].value;
console.log("Lake:|" + filterLake + "| Pets:|" + filterPets + "|");
$.ajax({
url: "/Estates/MapFilter",
type: "Post",
data: {
"filterLake": filterLake,
"filterPets": filterPets
},
success: function (result) {
filteredMapData = result;
console.log("Result = " + result);
loadMapMarkers(true)
}
});
};
})
When I run the program on localhost, I am able to reach the
console.log("Lake:|" + filterLake + "| Pets:|" + filterPets + "|");
line with no issues. Anything after does not run.
You need check filterPets value, it must be true/false then model binder can map with bool type.
With primitive type (bool, int, float) you should use nullable type bool? for preventing case the value incorrect format.
[HttpPost]
public ActionResult MapFilter(string filterLake, bool? filterPets)
{
}
With this paramter if filterPets has wrong value, it will be null.

How to pass the data from controller to view in mvc4

I am working on MVC4 application in that this is Actionresult returns json result but i want to pass variable objservice.callid on view but i am returning json can it is possible to get value on view with the help of json result or having any method to pass the value of variable to view but return type shoould be json result.
Here is code in controller:
[HttpPost]
public ActionResult create(ServiceCall objservice)
{
AllViewBags();
string result = PartnerMaster.CreateServiceCall(objservice);
if (result == "")
{
ViewBag.id = objservice.callID;
return Json("Service Call = " + objservice.callID + " is Created successfully!");
} else {
return Json("This record is not added because of this error:=>" + result);
}
}
Here is code in view:
if (str.indexOf("successfully") != -1)
{
window.location.href = '#Url.Action("edit", "service_call", new { id = "CC" })'.replace("CC", '#ViewBag.id');
} else {
if (str.search("added") != -1)
{
window.location.href = '#Url.Action("service_call", "service_call")';
} else {
window.location.href = '#Url.Action("edit", "service_call", new { id = "CC" })'.replace("CC", callID);
}
}
I have try that objservice.callid variable store in viewbag and access on view it is not work.because view is not return controller.
can it is possible to store that variable in session variable then access on view.
Please give some suggestion ....
return as a json object with multiple values
[HttpPost]
public ActionResult create(ServiceCall objservice)
{
AllViewBags();
string result = PartnerMaster.CreateServiceCall(objservice);
if (result == "")
{
return Json(new { message = "Service Call = " + objservice.callID + " is Created successfully!", id = objservice.callID);
}
else
{
return Json(new {message = "This record is not added because of this error:=>" + result, id = 0});
}
}
and use this in the post success to redirect ...

How to get account code to display in error message

I am trying to create some validation for a form.
The user can enter in account code, name, address, etc for companies. I need to create the validation for the name text box. If they enter a name that already exists then display the message "This name already exists on account code: " then display the account code.
The problem is I don't know how to get the account code of the company.
<asp:TextBox runat="server" ID="txtName" onblur="CheckIfNameExists(this.value)"></asp:TextBox>
function CheckIfNameExists(Name) {
PageMethods.CheckIfNameExists(Name,
OnCheckIfNameExists,
null
);
}
function OnCheckIfNameExists(result){
if(result){
alert("This Name already exists!");
}
else{
}
}
Web method for checking bool:
[WebMethod]
public static bool CheckIfNameExists(string Name)
{
try
{
if(Creditor.CheckIfNameCreditorExists(Company.Current.CompanyID, Name))
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return true;
}
}
Right now the code just checks if the name already exists in the database. But I want to get the account code of the name in the database.
This is the code that searches the database:
public static bool CheckIfNameCreditorExists(int CompanyID, string Name)
{
DataSet ds = new DataSet();
string sql = "proc_CheckIfACCreditorExists";
string query = "SELECT c.* " +
" FROM Creditor c " +
" WHERE c.Company_ID = " + CompanyID + " AND c.Name LIKE '" + Name + "' ";
DataTable dt = new DataTable();
using (MySql.Data.MySqlClient.MySqlDataAdapter adapter = new MySql.Data.MySqlClient.MySqlDataAdapter(query, DataUtils.ConnectionStrings["TAT"]))
{
adapter.SelectCommand.CommandType = CommandType.Text;
adapter.SelectCommand.CommandText = query;
adapter.Fill(dt);
if (dt.Rows.Count > 0)
{
return true;
}
return false;
}
}
Change the return type of your method to string from bool
bool is replaced with string in below code snippet
public static string CheckIfNameCreditorExists(...
Now, change your return type. I am just rewriting your return lines only.
if (dt.Rows.Count > 0)
{
//Make sure to use right column name here
return string.format("{Exist: true, AccountNo: {0}}", dt.Rows["AccNo"]);
}
return return "{Exist: false, AccountNo: null}";
Finally, modify javascript method as below.
function OnCheckIfNameExists(result){
if(result.Exist){
alert("This Name already exists!");
alert("Associated Account Number is: " + result.AccountNo);
}
else{
}
}
Only possible issue is: Sometimes, returned json string will not be parsed automatically. In that case rather than directly referring result, you can parse Json to object and use its properties in javascript method.
I would call the method using jquery.
jquery ajax
function CheckIfNameExists(Name) {
$.ajax("CheckIfNameCreditorExists?companyID=[value]&name=[value]").done(
function(result) {
if(result){
alert("This Name already exists!");
}
else {
}
});
}
You can do it in POST or GET as you wish.

MVC- After ajax request Page cannot be refresh

on my view page , i am passing some values to controller by ajax request , on controller action, after checking , redirecting message value to view's controller.Adding message to model and pasisng model to view again with new model value.On second time( postback) model values passed to view as Json but new model value(which is message) cannot be catch by javascript.In my code it is Model.INFO
$.ajax({
type: "POST",
url: '#Url.Action("TeamSaveChanges", "Administrator")',
data: {
ID: '#Model.ID',
doctorID: doctorValue,
nurseID:nurseValue,
driverID:driverValue,
technicianID: technicianValue
},
dataType: "text",
success: function () { alert("#Model.INFO")},
error: function () { alert("Error occured!!!") }
});
Controller
public ActionResult TeamSaveChanges(Guid ID, Guid? doctorID, Guid? nurseID, Guid? driverID, Guid? technicianID)
{
try
{
using (var client = SoapProxyFactory.CreateDSrvGDSoapClient())
{
var emptyTeam = Guid.Empty;
var ambID = client.getAmbulanceIDbyTeamID(ID);
var baseresult = client.checkAmblanceTeamsforDuplicateMembers(ambID, ID);
if (doctorID == emptyTeam && nurseID == emptyTeam && driverID == emptyTeam && technicianID == emptyTeam )
{
var result = client.EditTeamMembers(ID, doctorID, nurseID, driverID, technicianID);
if (result)
throw new Exception("saved");
}
else
{
foreach (var item in baseresult)
{
if(item.DOCTORCODE == doctorID && item.NURSECODE == nurseID && item.DRIVERCODE == driverID && item.TECHNICIANCODE == technicianID)
throw new Exception("The team with Same Members is exist." + "<p>(" + item.TEAMCODE + ")</p>");
}
var result = client.EditTeamMembers(ID, doctorID, nurseID, driverID, technicianID);
if (result)
throw new Exception("saved");
}
catch (Exception exp)
{
string message = exp.Message;
return RedirectToAction("TeamMembers", "Administrator", new { ID = ID, message = message });
}
[OutputCache(Location = System.Web.UI.OutputCacheLocation.None)]
public ActionResult TeamMembers(Guid? ID,string message)
{
try
{
if (!ID.HasValue())
return RedirectToAction("Ambulance");
using (var client = SoapProxyFactory.CreateDSrvALLSoapClient())
{
Guid id = ID.Value;
var clientGD = SoapProxyFactory.CreateDSrvGDSoapClient();
var result = client.GetTeamMembers(id);
result.INFO = message;
if (message != null)
{
result.INFO = message;
return Json(result,JsonRequestBehavior.AllowGet);
}
return View(result);
}
}
This line:
success: function () { alert("#Model.INFO")},
Will only pull in the INFO of the model once because it renders the server value in the client. If you are expecting it to change, then you have to pass the result back to success, and accept the new value as such:
success: function (d) { alert(d); },
To return a value to it you have to return from the action:
return Content("SOMEVAL"); // or PartialView or something that is string data
However, redirecting to action isn't going to return a response to the caller, and may not be handled properly through AJAX, so I'm not 100% sure what the question is...
Why would you use AJAX for this? What is happening is your script is firing a request off to your controller, which sends the response back as data, not a redirect to a new webpage.
Just create a form that POSTs those variables to your controller in typical MVC fashion, you'll get the result you want.

How to return line breaks in MVC JsonResult

I want to display a javascript alert using the message being passed back from a controller action that returns Json result. I want this message to have line breaks in it.
Here is my controller, note the "\n" to input line breaks:
[HttpPost]
public JsonResult CreatePO(PONewViewModel viewModel)
{
if (ModelState.IsValid)
{
var createPOResult = _managePOsAppServ
.CreateNewPOHeaderAndDetail(CurrentFacilityId, CurrentUserId, viewModel.VendorId,
viewModel.CustomerId, viewModel.OrderHeaderId, viewModel.ItemId, viewModel.QtyToOrder,
viewModel.UnitCost);
return Json(createPOResult, JsonRequestBehavior.AllowGet);
}
var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
string errorMessage = "";
if (modelStateErrors.Count() > 0)
{
foreach (var error in modelStateErrors)
{
errorMessage += error.ErrorMessage + "\n";
}
}
return Json(ActionConfirmation<int>.CreateFailureConfirmation(errorMessage, -1,false).Message, JsonRequestBehavior.AllowGet);
}
However, the \n is being displayed in the alert box. So it seems the returned Json is escaping the \n. How do I get it to be recognized as a line break?
Javascript:
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
hideLoading();
}
}
How are you alerting the data? Sounds like you're maybe alerting the JSON string, not the JavaScript string. Make sure you parse the JSON in your result by changing alert(xhr.responseText) to alert(jQuery.parseJSON(xhr.responseText));

Categories