Reputation: 4390
I need to separate my MVC view with jQuery that is in the top of the page. I am not sure what should I use instead of these lines:
This is data that is pass to Ajax call.
var data = {
'@Html.IdFor(model => model.SearchMethod)': searchMethod,
'@Html.IdFor(model => model.FirstName)': firstName,
'@Html.IdFor(model => model.LastName)': lastName
};
These are my textboxes in MVC:
@Html.DropDownListFor(model => model.SearchMethod, Model.AvailableSearchMethods, new { onchange = "toggleDIvDisplay(this.value)", id = "SearchMethod" })
@Html.TextBoxFor(model => model.FirstName, new { id = "FirstName" })
@Html.TextBoxFor(model => model.LastName, new { id = "LastName" })
I try this but it is not working. (it does not find any record as I thing can't get the value of the textboxed correctly.
var data = {
'$("#SearchMethod").val()': searchMethod,
'$("#FirstName").val()': firstName,
'$("#LastName").val()': lastName
};
and this is my complete Ajax call that is working when I use Html.IdFor.
$.ajax({
url: '@Url.Action("GetCustomer", "Doc")',
type: 'POST',
data: data,
dataType: 'json',
success: function (data) {
if (data && data.data) {
$.unblockUI();
renderResults(data.data);
}
Upvotes: 0
Views: 591
Reputation: 239290
Not sure what you're trying to do. In your first definition of data
, bear in mind that the keys are going to be just the property names, not the property names with in id notation (i.e. SearchMethod
, not #SearchMethod
. If you're trying to do something like use the key to query the element, you'll need to do $('#' + key)
.
Your second definition of data
makes no sense. 1) I'm not sure why you're redefining it in the first place, and 2) Enclosing the jQuery in quotes means that literally string will be set as the key, not the evaluation of it.
Upvotes: 1
Reputation: 13949
It looks like you may have the syntax backwards.. when you define your data
object the Name goes first and the Value second name: value
.
@Html.DropDownListFor(model => model.SearchMethod, Model.AvailableSearchMethods, new { onchange = "toggleDIvDisplay(this.value)"})
@Html.TextBoxFor(model => model.FirstName)
@Html.TextBoxFor(model => model.LastName)
this will give you the same markup as including the @id in htmlAttributes.. So for your data object you will want to use the Name of the parameter you're passing and then get the value from the inputs based on Id.
var data = {
searchMethod: $("#SearchMethod").val(),
firstName: $("#FirstName").val(),
lastName: $("#LastName").val()
};
You can see here that you do not need the single quotes around the Val() methods either.
Upvotes: 3