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
There are a couple of issues with your code:
idis a route value, not HTML attributeformCollectionwhen you should be serializing the data.So let’s start by fixing the markup first:
and then the script that will AJAXify the form:
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.