houman_ag houman_ag - 1 month ago 12
Javascript Question

How to obtain an entered data in a form inside Ajax.ActionLink?

My page is quite simple. It shows a picture and has a comment section (which is a partial view). I only want the partial view to refresh whenever a new comment has been submitted. So I have this:

<tr>
<td>@Html.TextBox("NewComment")</td>
</tr>
<tr>
@Ajax.ActionLink("Submit", "InsertComment", new
{
Id = Model.userParticipation.Id,
CurrentPosition = 0,
CurrentComments = Model.currentComments,
NewCommentText = "???"
},
new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "CommentSection"
})
</tr>


The only prolem I have is that I don't know how to pass the entered text in the NewComment TextBox to the NewCommentText variable (instead of the "???" string). Any help would be appreciated.

Answer

@Ajax.ActionLink is going to generate the markup for an anchor tag (with ajaxified behavior wired in). But since you want to submit a new comment to the server, you need an input field for user to enter the comment and potentially a form. If you want the ajaxified behavior for this form submission, you can use the Ajax.BeginForm helper method.

@using (Ajax.BeginForm("InsertComment", "Home", new
{
    Id = Model.userParticipation.Id,
    CurrentPosition = 0,
}, new AjaxOptions
{
    HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "CommentSection"
}))
{
    <label>Enter comment</label>
    <input type="text" name="NewCommentText" />
    <input type="submit" />
}
<div id="CommentSection"></div>

This will generate the form tag with an input element with name attribute value set to "NewCommentText".

This should work assuming your InsertComment action method (inside HomeController) has a parameter with the same name as the input field, along with the other paramters like Id and CurrentPosition.

[HttpPost]
public ActionResult InsertComment(string NewCommentText,int Id,int currentPosition)
{
    // to do : Save and return some valid markup
    return Content("To do : Replace this with useful html markup");
}
Comments