views:

518

answers:

2

Hello, I'm having some difficulties with Ajax.BeginForm

I have something like this in a view

  <% using (Ajax.BeginForm("ActionName", null , null, new { id = "FormName" }))
     {%>
      <input type="hidden" value = '<%= Html.Encode( Model.id) %>' name="id"/>
      <textarea id="message" name=message rows="4" style="width: 90%"> 
      </textarea>
  <% }%}

And the action method is something like this

    [AcceptVerbs(HttpVerbs.Post)]
    [Authorize]
    public ActionResult ActionName(int id, string message)
    {
     ....
    }

I'm trying to pass the 'id' and 'message' to the action method. I'm passing 'null' for routeValues but I dont know what to pass. Ideally I was trying to find an overload that did not require route values but took actionName and htmlattributes (for form name) but I could not find one.I don't want to add 'message' to the view-model and I do need the FormName in there for jquery operations. What is the best way to work around this problem ?

Oh, I forgot to mention, This is how I post the form

 $.post($("#FormName").attr('action'), $("#FormName").serialize(),
                               function(result) {
                                   $("#correspondingDiv").html(result);
                               }
                            );
A: 

Try:

  <% using (Ajax.BeginForm("ActionName", null))
     {%>
      <input type="hidden" value = '<%= Html.Encode( Model.id) %>' name="id"/>
      <textarea id="message" name=message rows="4" style="width: 90%"> 
      </textarea>
  <% }%}

I think you are over-complicating the the issue, ID and Message will get populated on the postback from the fields in the form so you don't need to specify them in the form declaration. You might also want to try Html.BeginForm() instead unless you really want an Ajax response.

Lazarus
I do need Ajax response and I also said I need to mention the FormName in Ajax.BeginForm as I have multiple forms in the page.
Bala R
+2  A: 

Use this overload: http://msdn.microsoft.com/en-us/library/dd470605.aspx

Ajax.BeginForm(
    string "ActionName",
    string "ControllerName",
    new routevalues {id="IDValue",message="MyMessage"},
    new AjaxOptions {OnBegin=[someFunction], OnFailure=[failureFunction] },
    new { id = "FormName" }
)
Dave Swersky
When I try this solution, the controller action method gets called but it still has the initial route values that are defined in BeginForm and not the ones filled out in the form. Any thoughts ?
Bala R
There is no way using the Ajax.BeginForm to populate the values from your form, because the BeginForm helper is called when the page is rendered. You can get the values of the form fields using Request.Form.
Dave Swersky