views:

160

answers:

4

If I have a textbox in my view:

<div><%= Html.TextBox("Comments", Model.Comments)%></div>

I want to post the contents of this textbox to the controller with an Ajax call. I only need this one value though, so I don't want to post the whole form back.

<%= Ajax.ActionLink("update", "UpdateComments", 
                new { comments = /* ????? */ }, 
                new AjaxOptions { HttpMethod="POST" })%>

How do I get the textbox value?

+2  A: 

Rather than writing server-side ajax code, you should use client-side Ajax (e.g. jQuery) to get the runtime value of the textbox and post that value.

Neil Barnwell
When you say "should", is there a reason why the way I tried is wrong, or do you just think it's not the easiest way?
fearofawhackplanet
It's just not that easy. Server code is more about request processing and response sending, the client is responsible for **making** the requests. In this case, you don't want to use a full-page POST of the form, so an Ajax POST is a suitable alternative (and jQuery makes it easier).
Neil Barnwell
A: 

You can use Ajax in jquery. Like this

function FunctionName() { $.Post(URl, function(data) {

    });
}
Amit
+2  A: 

using jQuery, you could retrieve the value in the following manner.

$("#Comments").val();
PieterG
+1  A: 

Ajax.ActionLink is a helper function, that generates a JS-enabled link, that sends data via AJAX. Because it is generated serverside, and the value is generated on the client side, you can not pass a single value like that. You either have to manually write HTML and JS, or submit a whole form containing this element (and watch out not to nest it inside another form).

Alexander