views:

497

answers:

4

i have a simple form on my page with a textbox and button that calls this javascript method

onclick="Create();"

and this is the function that is ran...

function Create() {
    var txt = document.getElementById("longTxt").value;

    if (txt == "Insert Name") {
        alert("You must provide a name");
        return;
    }

    var data = { Name: txt };
    $.post("/Home/Create", data, null, "json");
}

The action called inserts the name into the database and returns a string.

The method works it adds the posted name to my database but how do i use that string my method returns to display the returned string in my textbox.

Edit:

what is my method suppose to look like i have something like

    [AcceptVerbs(HttpVerbs.Post)]
    public JsonResult Create(string name)
    {
        string hash = repo.addName(name);
        return new JsonResult()
        {
            Data = new { data = hash }
        };

    }

when i add breakpoints and check it out it looks like it is working it does add the name. the callback function is used because i replaced the

$("#longUrl").val(json.PropertyReturned);

with an alert(json.PropertyReturned); to see if anything is even happening and i get the textbox but it says "undefined"

im really new to all of this maybe im just doing the method and return wrong. also intelisense does not show "json.PropertyReturned" as an option when it pops up after typing "json."

+5  A: 

Provide a callback as the third argument of the post call that will get the value returned from the method and put it in your textbox.

$.post("/Home/Create", data, function(json,textStatus) {
    $("#longTxt").val( json.data );
},"json");

If you need to handle errors as well, you might want to look at using $.ajax().

EDIT: You should probably use the controller's Json method instead of constructing the result using the default constructor. It's more convenient.

return Json( new { data = hash } );
tvanfosson
@tvanfosson, thank you for your reply. I still have a slight issue and I've updated my post to reflect it. Could you take a look.
Fatal510
@Fatal510 -- I should have pointed out that the name of the property I was using was fictious since I didn't know your actual structure. I've updated. Note I also give an alternative way to return the json result using the controller's Json method.
tvanfosson
@tvanfosson, Thanks for the additional information it really helped.
Fatal510
@tvanfosson - thanks for this answer, helped me a lot!
p.campbell
A: 

I think the third parameter is the callback function. Instead of a null, pass a function name there.

Dhana
A: 
$.post("/Home/Create", data, function(data) {
    $("#textboxid").val(data.PropertyName);}, "json")
Craig Stuntz
A: 

Provide a callback, or set the async to false.

Chad Grant