KentZhou
KentZhou

Reputation: 25573

How to get user input for Ajax.ActionLink call for action method?

Suppose I want to use ajax action link to save one field with no change for view.

Here is my view(it is a strongly-typed view bound to type Model):

   <%= Html.TextBox("myComment", Model.MyComment)%>
   <%= Ajax.ActionLink("SAVE", "SaveComment", "Home",
       Model, new AjaxOptions { HttpMethod = "POST"})
   %>

Here is my Action for ajax actionlink in controller:

[AcceptVerbs(HttpVerbs.Post)]
public void SaveComment(Model model)
{
    MyRepository repository = new MyRepository();
    Model mod = repository.GetModel(model.ID);
    mod.MyComment = model.MyComment;

    try
    {
        repository.Save();
    }
    catch(Exception ex)
    {
        throw ex;
    }          
}

The problem is: I can't get the user input in textbox for Mycomment in action method. Whatever user input in browser for Mycomment, when click on Ajax ActionLink SAVE, then I check the value from param model for Mycomment, there is nothing changed for MyComment.

Confused is: Model should be bound to view in bi-way. but for this case, it seems not. Then I changed the Ajax.ActionLink call to:

Ajax.ActionLink("SAVE", "SaveComment", "Home",
       new {commentinput =Model.MyComment, new AjaxOptions { HttpMethod = "POST"})

then changed action method signature as:

public void SaveComment(string commentinput)

I still can't get the user input.

How to get the user input in controller action method?

Upvotes: 3

Views: 5813

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

AFAIK Ajax.ActionLink doesn't allow you to easily get form values and post them with AJAX. There are some workarounds which seem quite hackish (looking at the last paragraph Adapting the URL Dynamically makes me cry).

Here's the jQuery way (I prefer it if compared to MS Ajax):

<%= Html.TextBox("myComment", Model.MyComment) %>
<%= Html.ActionLink("SAVE", "SaveComment", "Home", new { id = "saveComment" }) %>

And then unobtrusively attach a click event handler to the anchor:

$(function() {
    $('a#saveComment').click(function(evt) {
        $.ajax({
            url : this.href,
            data: {
                // Assuming your model has a property called MyComment
                myComment: $('#myComment').val()
            },
            success: function(data, textStatus) {
                // Comment saved successfully
            }
        });
        evt.preventDefault();
    });
});

Upvotes: 4

Related Questions