Tomasz Tomasz - 1 year ago 101
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


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 javacript function result as BeginForm parameter?

Answer Source

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");

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download