Tomasz Tomasz - 4 months ago 29
Ajax Question

MVC Ajax.BeginForm javacript parameters

I have Ajax form where url id need to be from javascript

@using(Ajax.BeginForm("Add","Comments", new { ArticleID = 3 }, new AjaxOptions { UpdateTargetId="Comments"}))


Where ActionID (3) should be replaced with javascrpt function result. Something like

js:

function GetArticleID()
{
return 3;
}


Razor:

@using(Ajax.BeginForm("Add","Comments", new { ArticleID = GetArticleID() }, new AjaxOptions { UpdateTargetId="Comments"}))


Controller:

public ActionResult Add(int ArticleID, Comment model)
{

}


How can i use javacript function result as BeginForm parameter?

Answer

The line @using(Ajax.BeginForm(" will be executed by razor on server. At that time it does not have any knowledge of the javascript methods in your client browser. So you cannot mix a javascript function there.

I prefer to write clean custom code to do the ajax form submit (instead of using Ajax.BeginForm) because it allows me to customize any way i want.

Keep your form as a normal form.

@using(Html.BeginForm("Add","Comments"))
{
   <input type="hidden" name="ArticleId" id="ArticleId" value=""/>
   <input name="CommentText" type="text" />
   <input type="submit" id="saveCmntBtn" />
}

Now listen to the click event of the submit button. Assign the ArticleId value to the input field, get the serialized version of the form and post to server. You may use jQuery serialize() method to get the serialized version of your form.

$(function(){

  $("#saveCmntBtn").click(function(e){
     e.preventDefault();
     $("#ArticleId").val(GetArticleID());
     var f=$(this).closest("form");
     $.post(f.attr("action"),f.serialize(),function(res){
       $("#Comments").append(res);
     });
  });

});
Comments