Use JSON data to assign scope variables in controller, not view - json

My application receives a JSON object with two boolean values. I am accessing the JSON data in my controller using the following:
$http.post('url-here', {"token": token })
.success(function(data) {$scope.tokenValidate = data;});
This is the JSON object I receive:
{valid: true, expired: false}
I am able to access this data within my view using the following:
{{ tokenValidate.valid }} or {{ tokenValidate.expired }}
Instead, because of the way I'm creating my view, I'd like to use these boolean values to assign strings to scope variables from within the controller, like this:
if ($scope.tokenValidate.valid) {
$scope.header = "Choose a new password";
} else if ($scope.tokenValidate.expired) {
$scope.header = "This link has expired.";
$scope.mesage = "Enter your email address to receive a new link."
} else {
$scope.header = "This link is invalid."
}
When I do this, the controller fails to read the JSON data correctly.
TypeError: Cannot read property 'valid' of undefined
Any help? My guess is that it has something to with the fact that when I access the JSON from the view, it has already been loaded, but when I try to access it from the controller, $scope.tokenValidate hasn't been assigned yet.

Maybe the values are strings, not bool
if ($scope.tokenValidate.valid=='true') {
$scope.header = "Choose a new password";
} else if ($scope.tokenValidate.expired=='true') {
$scope.header = "This link has expired.";
$scope.mesage = "Enter your email address to receive a new link."
} else {
$scope.header = "This link is invalid."
}

Before you use returned json data, first parse it and then use it.
$http.post('url-here', {"token": token })
.then(function(data) {
var data=JSON.parse(data);
if (data.valid) {
$scope.header = "Choose a new password";
} else if (data.expired) {
$scope.header = "This link has expired.";
$scope.mesage = "Enter your email address to receive a new link."
} else {
$scope.header = "This link is invalid."
}
});

Related

i cant send json to asp mvc using angularjs

im trying to send json parameter to asp request handler like this:
$scope.SaveCarUpgrades = function () {
var parameter = JSON.stringify(resultCarUpgrades);
$http.get("/ProfileEditor/saveUserCarUpgrades/" + $scope.useridCarUpgrades,
{ params: { name: parameter }}
).then(onsuccess, onfail);
function onsuccess(response) {
if (response.status == 200) {
$scope.saveUpgradesResult = "save upgrades success";
} else {
$scope.saveUpgradesResult = "save upgrades failed" + response.status;
}
}
function onfail(response) {
$scope.saveUpgradesResult = "save upgrades failed" + response.status;
// $scope.saveUpgradesResult = parameter;
}
}
c# request handler is something very simpe. its just for testing right now:
public string SaveUserCarUpgrades(string id)
{
string result = id;
var data = Request.QueryString["name"];
return id;
}
the problem is i always get 404 if if use json as parameter. (its a complex long json) but as simple json or simple string the response is fine. i dont think the problem is mime type as i set it in iis express in devcmd.
thank you for helping

MVC controller action not returning JSON

I am unable to get a json response from my controller action. The network shows as a post which is correct as I am posting a file to the server, however, needs a JSON response sent back to my view.
public JsonResult Upload(HttpPostedFileBase file, int id)
{
Homes thishomes= _db.Homes.FirstOrDefault(t => t.Id == id);
FileUploader fileupload = new FileUploader();
fileupload.PostIt(file.InputStream);
return Json(new { success = true, response = "File uploaded.", JsonRequestBehavior.AllowGet });
}
JQUERY using Dropzonejs:
Dropzone.options.DropzoneForm = {
paramName: "file",
maxFilesize: 2000,
maxFiles: 28,
dictMaxFilesExceeded: "Custom max files msg",
init: function () {
this.on("success", function () {
alert("Added file");
})
}
};
Can anyone see an this issue?
Try to write [HttpPost] attribute over your action. Also "The network shows as a post which is correct" if its post then you don't need JsonRequestBehavior.AllowGet
when you are returning Json to your request

Retuning a JsonResult

I'm trying to return text to a message box when an error occurs and the return type is JsonResult.
I believe I'm returning a valid type, but when the messagebox appears, it says "undefined".
I have the Json set up as the following:
string maxChars = "Upload file size exceeded!";
return Json(new { MaxCharacters = maxChars });
What am I doing wrong?
If you are returning this json data from an HttpGet action method, you should explicitly tell the Json method to allow sending back the json data for a GET request.
public ActionResult YourMethod()
{
string maxChars = "Upload file size exceeded!";
return Json(new { MaxCharacters = maxChars }, JsonRequestBehavior.AllowGet);
}
And in your client side code, you should be accessing the MaxCharacters property of the response coming back from the ajax call.
$.get("#url.Action("YourMethod","YourControllerName")",function(res){
alert(res.MaxCharacters);
});

Can i return a Partial view and a Json object from my action method at the same time

i have the following action method, that returns a partial view _create. but is there a way to pass a Json object such as return Json(new { IsSuccess = "True" }, with the Partial view.
My Action method looks as follow:-
try
{
if (ModelState.IsValid)
{
var v = repository.GetVisit(visitid);
if (!(v.EligableToStart(User.Identity.Name)))
{
return View("NotFound");
}
vlr.VisitID = visitid;
repository.AddVisitLabResult(vlr);
repository.Save();
ViewBag.LabTestID = new SelectList(repository.FindAllLabTest(), "LabTestID", "Description", vlr.LabTestID);
// return Json(new { IsSuccess = "True" }, JsonRequestBehavior.AllowGet);
#ViewBag.status = "Added Succsfully";
return PartialView("_create",vlr) ;
}
}
::-UPDATED-::
what i am trying to do as follow:-
i am calling the action method using ajax.beginform
using (Ajax.BeginForm("CreateAll", "VisitLabResult", new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = item.ToString(),
InsertionMode = InsertionMode.Replace,
OnSuccess = string.Format("disableform({0})", Json.Encode(item)),
}))
after successfully receiving the response from the server ,, the Onsuccess script will be executed,,, the script simply disable the form:-
function disableform(id) {
$('#' + id + ' :input').prop("disabled", true);
}
The problem is that the script will always disable the form even is some validation error occurs,, so what i was trying to achieve is to return a JSON with the partial view that indicate if the ModelState.IsValid was valid or not,, and if it was not valid to keep the form enabled to allow the user to correct the validation errors.
BR
You can return ONLY ONE view from action method, if at all you want to pass other information,make use of ViewData or ViewBag
ViewBag.IsSuccess = "True";
Or
ViewData["IsSuccess"] = "True";
No, you can return only the view and pass JSON as the model, or ViewBag (I recommend model.)
Why not simply extend the model that you are already passing to the View adding the property IsSuccess?
ViewBag or ViewData are evil in my opinion. Try to always use a ViewModel when returning data to the view.
In such cases I used following solution:
In your ajax form definition set:
OnComplete = "yourCallback"
Then:
yourCallback = function(response){
var json = response.responseJSON;
if(json.success){
alert('Well done!');
} else {
var form = $('#formId');
form.html(json.html);
form.removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(form);
}
}
Your controller should return something like this:
var result = new { success = false, html = helper.Partial("_YourPartial", model) };
return Json(result);
Where helper helps you to add validation to your partial view. (Described here: https://stackoverflow.com/a/4270511/952023)

MissingMethodException showing up on save action

I'm working an example from Grails in Action, specifically implementing a Service for the first time and shifting the work from the Controller to the Service.
I have a Post object containing a User and String content.
The service code is
class PostService {
boolean transactional= true
Post createPost(String user, String content){
def thisUser = User.findByUserID(user)
if (user){
def post = new Post(content:content)
if (user.save()){
return post
} else
throw new PostException(message: "Invalid post", post:post)
}
throw new PostException(message:"Invalid User ID")
}
}
and the controller code is
def addPost = {
try{
def newPost = postService.createPost(params.id, params.content)
flash.message= "Added new Post: $newPost.content}"
} catch (PostException pe){
flash.message = pe.message
}
redirect(action:'timeline', id:params.id)
}
The way this code is supposed to work is an input is made in the form, which is passed to addPost as a params object. Said params object is then handed off to the Service, where a new Post is to be made and bound to the User.
However, I'm getting the error at user.save(). The specific error message is
No signature of method: java.lang.String.save() is applicable for argument
types: () values: []
If I erase the service connector and implement the service code in the controller as
def user = User.findByUserID(params.id)
if (user) {
def post= new Post(params)
user.addToPosts(post)
if (user.save()){
flash.message= "Sucessfully created Post"
}
else {
user.discard()
flash.message = "Invalid or empty post"
}
} else {
flash.message = "Invalid User ID"
}
redirect(action: 'timeline', id:params.id)
}
the action works. So why am I getting a user.save() error on the service implementation, but not the controller?
user is the String you're passing to the service method. thisUser is the actual User object you're getting that you can call save() on.