2

I have an AJAX form where the url id needs to be from JavaScript

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

Where ArticleID = 3 should be replaced so that the ArticleID value is set equal to the result of a called Javascript function. 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 JavaScript function result as BeginForm parameter?

3
  • What is your question? Commented Jul 16, 2016 at 22:15
  • How can i use javacript function result as BeginForm parameter? Commented Jul 16, 2016 at 22:17
  • Add that to your question so the users can understand it better. Commented Jul 16, 2016 at 22:17

1 Answer 1

3

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

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.