I am trying to adapt the following code
$(“#artistSearch”).submit(function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr(“action”),
data: form.serialize(),
beforeSend: function () {
$(“#ajax-loader”).show();
},
complete: function () {
$(“#ajax-loader”).hide();
},
error: searchFailed,
success: function (data) {
$(“#artistTemplate”).tmpl(data).appendTo(“#artist-list”);
}
});
from Professional ASP.NET MVC 3 to allow searching and returning data within the same form and ended up with the following:
On a separate script file
$(function () {
$("#btnSearch").click(function (event) {
event.preventDefault();
var idno = $("#txtIdNo").value;
$.ajax({
url: "/Owner/Search",
type: "POST",
data: idno,
datatype: "json",
beforeSend: function () {
$("#FullName").html("");
$("#OwnerId").html("");
$("#notFound").html("");
$("#ajax-loader").show();
},
complete: function () {
$("#ajax-loader").hide();
},
error: function () {
$("#notFound").html("Sorry, no data returned."); ;
},
success: function (data) {
$("#OwnerId").html(data.OwnerId);
$("#FullName").html(data.FullName);
}
});
});
});
On the Controller
[HttpPost]
public JsonResult SearchById(string idNo)
{
var owner = _ownerService.FindBy(x => x.IdNo == idNo);
return Json(owner);
}
On the View
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<div>
<p>
Id No:
<input type="text" name="txtIdNo" />
<input type="button" value="Search" name="btnSearch" />
<label id="notFound"></label>
</p>
@Html.Hidden("OwnerId")
.
.
.
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
The reason I am using
within the view is to avoid two submit buttons within the same form because I realized the form was validating after clicking on the search button.
I have also looked at the suggested similar questions before asking with no avail.
I have been unable to make the above work and would appreciate any help offered.
I am a newbie to MVC3 and JQuery
jquery ID Selector (“#id”) – Selects a single element with the given id attribute.
You are using jquery ID Selector, but you donot have the id attribute on the from elements.
Add id attribute to your form elements.
Edit the jQuery ajax function: data: {idNo:idno}