0

i'm trying to post a form to my controller via ajax so i can render a partial view.

Here is my Ajax Code

 var formCollection = $('#some-form');
 $(function(){ $('#some-form').submit(function(){
      $.ajax({
           type: "POST",
           url: "/Trusk/Index",
           data: formCollection,
           dataType: "html",
           success: function (result) {
               $('#newView').html(result);
           },
           error: function (request, status, error) {
               alert('Oh no!');
           }
     });
});
}); 

Code for my form, i want partial view to be render at ID = newView, The partial view is returned by the controller

  <% using (Html.BeginForm(new { @id = "some-form" }))
           { %>
            <div id="TestDiv">
            <div id="Title">Test</div>                 
                <div id="CheckIn">Check-in:<br />
                <%:Html.TextBox("FromDate", "", new { @id = "DateFrom", @style =  "width:190px" })%></div>
                <div id="CheckOut">Check-out:<br />
                <%:Html.TextBox("ToDate", "", new { @id = "DateTo", @style =  "width:190px" })%><br /></div>
                <div id="newView">  
                </div>
                <input type="submit" value="Search" />        
        </div>
               </div>
        <% } %>

My controller code

 public ActionResult Index(FormCollection post)
    {
        ITruckRepository hotelRep = new TruckRepository();

        IEnumerable<Truck> AvailableTrucks = hotelRep.getTrucks('2012,3,2', '2012,3,5');

       return PartialView("Search", AvailableTrucks );

    }

Do i pass the correct parameter to the controller via Ajax?

Thanks

1
  • There is two way to post URL 1. *@using (Ajax.BeginForm("Action", "controller", new AjaxOptions { HttpMethod = "post", OnSuccess = "AddEditOnsuccess(Data)", OnBegin = "AddEditOnbegin", OnFailure = "AddEditOnfail" }, new { enctype = "multipart/form-data", id = "frm", @class = "apply-nolazy" })) 2. With Ajax request and do data: $(this).serialize(), Commented May 7, 2015 at 10:36

2 Answers 2

2

There are a couple of issues with your code:

  • You are using a wrong overload of the Html.BeginForm method. In the overload you used the id is a route value, not HTML attribute
  • Inside your .submit callback you are not canceling the default action by returning false and thus when the form is submitted the AJAX call will hardly have any time to execute before the browser redirects away from the page
  • In the data parameter of the AJAX call you are passing a jQuery object representing the form called formCollection when you should be serializing the data.
  • You have broken markup => there's one closing div that doesn't have a corresponding opening element.

So let's start by fixing the markup first:

<% using (Html.BeginForm(null, null, FormMethod.Post, new { id = "some-form" })) { %>
    <div id="TestDiv">
        <div id="Title">Test</div>                 
        <div id="CheckIn">
            Check-in:<br />
            <%= Html.TextBox("FromDate", "", new { id = "DateFrom", style = "width:190px" }) %>
        </div>
        <div id="CheckOut">
            Check-out:<br />
            <%= Html.TextBox("ToDate", "", new { id = "DateTo", style = "width:190px" }) %>
            <br />
        </div>
        <div id="newView"></div>
        <input type="submit" value="Search" />        
    </div>
<% } %>

and then the script that will AJAXify the form:

$(function () {
    $('#some-form').submit(function () {
        $.ajax({
            type: this.method,
            url: this.action,
            data: $(this).serialize(),
            success: function (result) {
                $('#newView').html(result);
            },
            error: function (request, status, error) {
                alert('Oh no!');
            }
        });
        return false;
    });
}); 

Now you should ensure that the corresponding POST controller action is successfully invoked and the parameters passed correctly. Also ensure that no errors occur inside this controller action and while rendering the partial view. Use a javascript debugging tool such as FireBug to see exactly what request/response are being sent as well as any possible js errors.

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

1 Comment

Life saver Mate! been struggling with this problem for 3 hours, and you solved it in no time! Appreciate it a lot, Thanks buddy!
0

You need to call .Serialize() on formCollection - which will encode the form as a string for submission.

var formCollection = $('#some-form'); 
$(function(){ $('#some-form').submit(function(){ 
  $.ajax({ 
       type: "POST", 
       url: "/Trusk/Index", 
       data: formCollection.serialize(), 
       dataType: "html", 
       success: function (result) { 
           $('#newView').html(result); 
       }, 
       error: function (request, status, error) { 
           alert('Oh no!'); 
       } 
 }); 
});
});  

Also, while you have a FormCollection parameter on your controller method - you're not actually using it?

3 Comments

i will be using it, Still not working my partal view is geting posted at this URL for some reasons localhost:5927/Trusk/Index/some-form instead of being posted on the index page under newView id.
can it be the way form id is added, to the form?
i have got it kinda working, though now it shows me the alert('Oh no')

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.