George George - 4 months ago 7
JSON Question

Compare from Json result

I have action which returns JSON

[HttpPost]
public JsonResult Validate(string arg1, string arg2)
{
bool check
...
return Json(!check ? new { message = "-1" } : new { message = "1" }, JsonRequestBehavior.AllowGet);
}


And I need to call that action from another action. I need that comparison for client side call (using ajax) and plus for server side validation in another post action.

How can I get message from that action?

var a = Validate(model.arg1, model.arg2);
a.Data;


returns json. How can I get value from it to compare something?

Answer
  1. create a new class file. let's say you name it helper.cs.

    namespace YourProject.Helper{ public class Helper{ // your validation code goes here. } }

  2. import this class in your controller by using YourProjectNS.Helper

    using MyProject.Helper;

  3. define the Validate function in helper class.

    public class Helper{ public bool Validate(string arg1, string arg2){ bool check ... return Json(!check ? new { message = "-1" } : new { message = "1" }); } }

  4. In your controller, wherever you need it, access it as helperObj.Validate(v,v2)

    Helper helperObj = new Helper(); bool isValid = helperObj.Validate(v1, v2);

Ultimately your code will look something like:

in Helper.cs:

namespace MyProject.Helper{
    public class Helper{
        public bool Validate(string arg1, string arg2)
        {
            bool check
            ...
            return Json(!check ? new { message = "-1" } : new { message = "1" });
        }
    }
}

in your controller action:

using MyProject.Helper;

public ActionResult MyAction(){
    ...
    // your other code
    Helper helperObj = new Helper();
    bool isValid = helperObj.Validate(v1, v2);

    ...
}

Hope this helps.