1

How do I access an object returned from the database with Javascript

This function is called from Javascript

function searchUser() {
    var userName = document.getElementById('UserName').value
    $.post("SearchForUser", { userName: userName }, function (UserInfo) {

        UserInfo; //How to access the returned UserInfo properties?

    });
}

I Use this code to get the UserInfo from the database

    public UserInfo SearchForUser(string userName)
    {
       string password = "nicola";

        using (FormValueEntities db = new FormValueEntities())
        {
            //Query the database for the user
            UserInfo userInfo = new UserInfo();
            userInfo = db.UserGet(userName, password).FirstOrDefault();
            return userInfo;
        }
    }

The UserInfo has the Following properties : UserName, UserPassword and Description

3 Answers 3

1

It'd be better if you returned a JsonResult

public JsonResult SearchForUser(string userName)
{
     ...
     return Json(userInfo, JsonRequestBehavior.AllowGet);
     //you don't need the AllowGet if this is a POST action, cannot tell
}

Then in JavaScript you can have easy access to your model, e.g.

$.post("SearchForUser", { userName: userName }, function (UserInfo) {

        console.log(UserInfo.UserName) ; 

    });
Sign up to request clarification or add additional context in comments.

Comments

0

The second part of your script is server side Java I assume.

You can't just return it like that, what jQuery does is make a http request to the server and the server will then send a response back.

As dove commented you can format your response as JSON and use the jQuery.getJSON on the client side.

Comments

0

You can have your action return from the method Json . This will JSON-serialize the object you give it and return a JsonResult.

public ActionResult Search(string usernameName)
{
    return Json(SearchForUser(userName)); // borrows the result of your SearchForUser method and returns it as JSON-serialized string.
}

JsonResult should set the response content type to "application/json", so that means that jQuery's $.post should see that response header and automatically deserialize it.

function searchUser() {
    var userName = document.getElementById('UserName').value
    $.post("Search", { userName: userName }, function (UserInfo) {

        alert(UserInfo.Description); // example of consuming the deserialized JSON messsage.

    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.