Reputation: 15
I have a controller action method which returns a partial View and I am calling the controller action method from the Main Index View like below.
public PartialViewResult GetEmployee(int val)
{
var employee = db.getEmployeeById(val)
return PartialView("_PatialEmployeeView", employee);
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Get Employee</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Input)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Input)
@Html.ValidationMessageFor(model => model.Input)
</div>
<p>
<input id="GetEmp" type="submit" value="Run" />
</p>
</fieldset>
}
<div id="EmployeeResults">
</div>
And my Javascript to make the AJAX request is as below.
$('#GetEmp').click(function (e) {
var empId = document.getElementById("GetEmp").value;
$.ajax({
url: '@Url.Action("GetEmployee", "Home")',
type: "get", //send it through get method
data: { val: empId },
cache: false,
success: function (data) {
$("#EmployeeResults").html(data);
//Do Something
},
error: function (xhr) {
alert("FAILED");
//Do Something to handle error
}
});
});
In above, whenever i enter employee id value in the text box and submit the form...I want to attach the results from the partial View to the div (EmployeeResults) element. I get the partial View results back, but the whole page gets refreshed everytime i submit the form and as a result I don't see the partial view output.
Could someone point what I am doing wrong and how I can display just the partial view without refreshing the whole page.
Upvotes: 1
Views: 1740
Reputation: 27012
Submitting a form causes the page to refresh, unless you prevent the default action:
$('#GetEmp').click(function (e) {
e.preventDefault();
Upvotes: 1