0

I add a link dynamically to a page, and I want the "name" property to be a value that is sent back from server.

This is the code I have for adding a song to the server and then I dynamically append link to my song with a delete button, and I want that button to have a name equal to the songID evaluated on the server side.

  $.ajax({
            url: "/Home/AddSong",
            type: "POST",
            data: $("#AddTopTenFavForm").serialize(),
            success: function () { ShowMsg("Song Added Successfully"), $(container).find('ul').append('<li><a class="topTenFavLinks" href="#" name="' + substr + '" >' + name + '</a> <span name= @item.SongId class="btnDeleteSong dontDoAnything">x</span></li>'); },
            error: function () { ShowMsg("There was an error therefore song could not be added, please try again") }
        });

here is my mvc action:

    [HttpPost]
    public ActionResult AddSong(HomeViewModel songModel)
    {
        var song = new Song();
        song.GenreId = songModel.topTenFav.Rank;
        song.Date = DateTime.Now;
        song.UserName = User.Identity.Name;
        song.Title = songModel.topTenFav.Title;
        song.YoutubeLink = songModel.topTenFav.YoutubeLink;
        repository.AddSong(song);
        repository.Save();
        return RedirectToAction("Index");

    }

How would I solve this issue in a single ajax request?

2 Answers 2

2

You need to return your song ID from the action

[HttpPost]
public ActionResult AddSong(HomeViewModel songModel)
{
    //code goes here
    return this.Content(song.Id.ToString());

}

and in the javascript success callback you will receive data in arguments:

success: function (data) { /* use data here for anchor name */ },
Sign up to request clarification or add additional context in comments.

4 Comments

in my action I have return RedirectToAction("Index"); how would I change this to return to index and return json at the sam etime?
And after Ajax call your page redirects to the Index?
so the redirect to index in my action is unnecessary if I only call that action method through ajax?
you can return redirect if it's not ajax call if you needed. But for described scenario you need to return data to the client, not redirect. You can get know if it's ajax request from the Request.IsAjaxRequest().
1

Use JsonResult to return your Id, and append to your link.

Look at examples

http://shashankshetty.wordpress.com/2009/03/04/using-jsonresult-with-jquery-in-aspnet-mvc/

http://geekswithblogs.net/michelotti/archive/2008/06/28/mvc-json---jsonresult-and-jquery.aspx

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.