Tomasz Tomasz - 4 months ago 72
Javascript Question

MVC Ajax.BeginForm JavaScript parameters

I have an 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


function GetArticleID()
return 3;


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


public ActionResult Add(int ArticleID, Comment model)


How can I use JavaScript function result as BeginForm parameter?


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.

   <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.


     var f=$(this).closest("form");