Handling objects and routes with MVC3/Razor? - asp.net-mvc-3

I have a geo collection that contains items like:
[state name]
[city], [state]
[country]
A text box is available for a user to begin typing, and a jQuery autocomplete box fills displays possible options.
The URL structure of the post request will depend on which was selected from the collection above, ie
www.mysite.com/allstates/someterms (if a country is selected)
www.mysite.com/city-state/someterms (if a city, state is selected)
www.mysite.com/[state name]/someterms (if a state is selected)
These are already defined in my routes.
I was initially going to add some logic on the controller to determine the appropriate URL structure, but I was thinking to simply add that as an additional field in the geo table, so it would be a property of the geo collection.
Here is my jQuery function to display the collection details when, fired on keypress in the textbox:
$(function () {
$("#txtGeoLocation").autocomplete(txtGeoLocation, {
source: function (request, response) {
$.ajax({
url: "/home/FindLocations", type: "POST",
dataType: "json",
selectFirst: true,
autoFill: true,
mustMatch: true,
data: { searchText: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.GeoDisplay, value: item.GeoDisplay, id: item.GeoID }
}))
}
})
},
select: function (event, ui) {
alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
: "Nothing selected, input was " + this.value);
document.getElementById("hidLocation").value = ui.item.id;
}
});
});
What I would like is to have structure the URL based on an object parameter (seems the simplest). I can only seem to read the parameters on "selected", and not on button click.
How can I accomplish this?
Thanks.

To resolve this, I removed the select: portion from the Javascript, and added the selected object parameters in the MVC route sent to my controller.

Related

Jqgrid custom form and custom function

I have the following problem. I m using a custom form for Jqgrid, the problem is that I can t figure it out how can I use different functions for submit button in add/edit/delete. Can you help me? I can use delfunc with succes. How can I add delfunc to the button submit from del form, and the function addfunc to submit button from the form of add.
$('#jqGrid').navGrid("#jqGridPager", {
edit: true,
add: true,
del: true,
refresh: true,
view: false,
addfunc : function(){
var angajat = new Object();
angajat.id = null;
angajat.firstName = "andrei" //jQuery("#jqGrid").jqGrid('getRowData');
angajat.lastName = " chivu " //jQuery("#jqGrid").jqGrid('getRowData');
console.log(angajat);
$.ajax({
type: "POST",
url: "rest/user/add",
data: JSON.stringify(angajat),
contentType: "application/json; charset=utf-8",
dataType: "json",
contentType: "application/json",
success: function (data) {
$("#response").html(JSON.stringify(data));
}
});
},
delfunc : function (id){
$.ajax({
type:"DELETE",
url:"rest/user/delete",
data:JSON.stringify(id),
dataType: "json",
contentType: "application/json",
}).done(function( msg ) {
alert("Content Deleted: " + id);},
jQuery("#jqGrid").trigger("reloadGrid"));
},
editCaption: "Update Employee",
template: template,
//onClick: alert("alaaaaa"),
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Add Dialog
{
addCaption: "Add new Employee",
template: template,
sData: alert("alaaaaa"),
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dialog
{
caption: "Delete the Employee",
msg: "Are you sure ? ",
beforeSubmit: alert("alaaaaa"),
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
},
});
});
One don't need to use delfunc, addfunc, editfunc or viewfunc in the most cases. The function are replacements for delGridRow, editGridRow and viewGridRow, but to replace the methods which code is not so small one have to understand the code in details.
I try to explain your problem how I understand it. I'll start with the usage of delfunc. What you try to do is calling of URL rest/user/delete using HTTP DELETE. Thus I suppose that you have RESTful services on the backend. To use HTTP DELETE you need to append the id of deleted item to the URL, use DELETE operation and be sure that no other information (like oper parameter) are placed in HTTP body. Thus you can use existing options of delGridRow.
It's important to understand that navGrid just add some buttons in the navigator bar and it calls the methods delGridRow, editGridRow and viewGridRow if the user clicks on the corresponding buttons. The options of navGrid looks like
$("#gridid").jqGrid('navGrid','#gridpager', {parameters},
prmEdit, prmAdd, prmDel, prmSearch, prmView);
(see the documentation). The parameters parts are real options of navGrid and it informs navGrid for example which buttons should be included on the navigator bar. The other options are the options of delGridRow, editGridRow, searchGrid and viewGridRow methods which shoule be used if the user clicks on the corresponding button of navigator bar. To configure the behavior of Delete button we need to specify prmDel parameter. The value of the parameter should be object with the properties and
callbacks of delGridRow method. See the documentation.
In the same way if one uses formatter: "actions" or inlineNav then another buttons will be added and one have to use the corresponding options to specify, which options of delGridRow should be used.
I find that the options of navGrid is difficult to understand. Because of that I introduced in free jqGrid alternative way of specify default options used in jqGrid by delGridRow inside of formDeleting of jqGrid options. Thus the most free jqGrid looks like the demo. It uses formEditing, formViewing, searching options of jqGrid and the call of navGrid is either without any parameters or with the small set of options. Now back to your main problems. See the wiki for more information.
If the main logic is clear then it will be clear how one configure jqGrid to do on Delete exactly what you need. To do this you should specify mtype: "DELETE" option and ajaxDelOptions: {...} to specify other options of Ajax call. To append the id to the URL you can use onclickSubmit or beforeSubmit callbacks (see the answer), but in free jqGrid and can use url defined as function (see the answer) and have more readable code. Thus I suggest you to use formDeleting option with the value
{
mtype: "DELETE",
url: function (rowid) {
return "/rest/user/delete/" + rowid;
},
ajaxDelOptions: { contentType: "application/json" },
serializeDelData: function () {
return "";
},
reloadGridOptions: { fromServer: true },
}
The grid will be reloaded automatically on successful deleting because reloadAfterSubmit: true is default option of delGridRow (see here). The last option reloadGridOptions is helpful in case of usage loadonce: true option of jqGrid. It will force reloading of grid from the server.
In the same way to configure Add and Edit buttons you can use formEditing option of jqGrid with the value
{
url: function (id, editOrAdd) {
return "/rest/user/" + (editOrAdd === "add" ? "add" : "edit");
},
mtype: function (editOrAdd) {
return editOrAdd === "add" ? "POST" : "PUT";
},
serializeEditData: function (postData) {
return JSON.stringify(postData);
},
serializeEditData: function (postData) {
var dataToSend = $.extend({}, postData); // make copy of data
// don't send any id in case of creating new row or to send `0`:
if (dataToSend.id === "_empty") {
delete dataToSend.id; // or dataToSend.id = 0;
}
return JSON.stringify(dataToSend);
},
ajaxEditOptions: { contentType: "application/json" },
reloadGridOptions: { fromServer: true }
}

autocomplete functionality on dynamic textbox

I have a scenario as follows,
Need to put autocomplete functionality on dynamic textbox with onkeyup functionality
My code is as follows, Here i have invoked a function "GetName" on buttonclick where am loadin the dynamic textboxes
function GetName() {
var dataToSend = JSON.stringify({ prefixText: $('#search').val(), Id: $("#SearchType").val()
});
$.ajax({
type: "POST",
data: { jsonData: dataToSend },
url: "GetName",
datatype: "json",
success: function (result) {
$("#ResourceNames").empty();
$("#ResourceNames").append('<table>');
$.each(result, function (i, Name) {
$("#ResourceNames").append('<tr><td ><Label>' + Name.Value + '</label></td><td> <input type="text" id="Supervisor" class = "form-control", onkeyup="GetResource(\'' + Name.Text + '\');"/></td></tr>');
});
},
error: function (xhr, status) {
alert(status);
}
})
$("#ResourceNames").append('</table>');
}
Here onkeyup event of textbox supervisor am calling the below function getresource with an argument
function GetResource(i) {
debugger;
var dataToSend = JSON.stringify({ prefixText: $("#Supervisor").val(), designation: i });
$.ajax({
url: "GetSupervisor",
data: { jsonData: dataToSend },
dataType: 'json',
type: 'POST',
success: function (data) {
$("#Supervisor").autocomplete({source:data});
});
},
error: function (error) {
alert('error; ' + error.text);
}
});
}
am not able to bind autocomplete data to dynamic textbox, can anyone help me out on the same?
You have several issues in your code:
First of all jQuery doesn't concatenates strings into DOM, it creates a DOMElement. So,
$("#ResourceNames").append('<table>'); will append an entire <table> element. Anything you append to #ResourceNames will be added after the table, not inside it.
The HTML you're appending contains id. So there can be multiple elements with same id which is invalid, depending on the response. It's better to use a common classname for those elements instead.
You don't need to manually handle the keyup event. You can specify the url you want to hit as the value of the source option of autocomplete, provided it returns a response suitable for the autocomplete. see this example in docs.
Instead of passing the value via the inline handler, you can store the value as a data-* attribute and access it later.
So your code should be something along:
function GetName() {
var dataToSend = JSON.stringify({ prefixText: $('#search').val(), Id: $("#SearchType").val()});
$.ajax({
type: "POST",
data: { jsonData: dataToSend },
url: "GetName",
datatype: "json",
success: function (result) {
var htmlString ="<table>";
$.each(result, function (i, Name) {
htmlString +="<tr><td ><Label>" + Name.Value + "</label></td><td> <input type='text' class = 'form-control Supervisor' data-name='"+ Name.Text + "'/></td></tr>";
});
},
error: function (xhr, status) {
alert(status);
}
})
$("#ResourceNames").append(htmlString);
$(".Supervisor")..autocomplete({
source: "GetSupervisor" // where GetSupervisor is your data source
});
}
If you want to manually send requests along with data and pass the results into the autocomplete, you can specify an function as the value of source option. (See my another answer for more info). for example:
$(".Supervisor").autocomplete({
source: function(request,response){
/*send the request here.
request.term contains the current value entered in textfield
pass the results you want to display like response(data)*/
}
});
Read the API documentation, play with it for a while and you'll be able to get it working.

Auto complete (Jquery) focus doesn't bind Spring Propety

I am working on Auto complete (jquery) using Spring MVC. I have done everything, data is displaying properly in auto complete but properties doesn't display onfocus event. Whenever i call "ui.item.username" in onfocus method, it always display me null value.
$( "#city" ).autocomplete({
minLength: 0,
source: function( request, response ) {
$.ajax({
url: "person.ajax",
dataType: "json",
data: {
maxRows: 6,
startsWith: request.term
},
success: function( data ) {
response( $.map( data.zipcodes, function( item) {
return {
label: item.realName + item.realName,
value: item.username
}
}));
}
});
},
it works fine till here but when i call property in onfocus methods (in following method), it displays me null
in focus event (jquery)
focus: function(event, ui) {
alert($( event.target ).val(ui.item.ealName)); // it displays me null value at this point
},
select: function( event, ui ) {
}
Any Suggestion?
The result object you're building in the success function of your AJAX request is used across all methods/event handlers of the autocomplete widget. If you want to access a property later, you'll have to include that property when you're building the data source you're passing to the response function:
success: function( data ) {
response( $.map( data.zipcodes, function( item) {
return {
label: item.realName + item.realName,
value: item.username,
realName: item.realName // include realName
}
}));
}
(From the comments):
Also the alert function does return null, so if you'd like to alert just the value, use:
alert(ui.item.realName)
instead.
I have implemented auto complete drop down using spring mvc. Now my question is when any user select/choose any value from auto complete drop down, then How can i sure that the selected value is correct or not? in other words i want to ensure that whether user selected the correct value from auto complete or not. Because user can type random string in input text box and submit it(Technically, i also make sure when user select any value from drop down, then submit will be visible to the user, and if user type incorrect data, the button shouldn't be activate).
Here is a code
<script>
$(function() {
$( "input[name='creditCheck']" ).autocomplete({
minLength: 2,
source:function( request, response ) {
$.ajax({
url: "creditCheck.ajax",
dataType: "json",
data: {
maxRows: 6,
startsWith: request.term
},
success: function( data ) {
response( $.map( data.creditCheckData, function( item) {
return {
creditName: item.creditName,
}
}));
}
});
},
The above code words fine, it get the list from server and displays the auto complete data.In following code i am just toggling the button.But i also make sure when user select any value from drop down, then submit will be visible to the user, and if user type incorrect data, the button shouldn't be activate.
$('input[name="creditCheck"]').bind("change keyup", function () {
if ($(this).val()!="") {
$(this).nextAll("button[name='add']:first").removeAttr('disabled');
} else {
$(this).nextAll("button[name='add']:first").attr('disabled', 'disabled');
}
});

jquery autocomplete using mvc3 dropdownlist

I am using ASP.NET MVC3 with EF Code First. I have not worked previously with jQuery. I would like to add autocomplete capability to a dropdownlist that is bound to my model. The dropdownlist stores the ID, and displays the value.
So, how do I wire up the jQuery UI auto complete widget to display the value as the user is typing but store the ID?
I will need multiple auto complete dropdowns in one view too.
I saw this plugin: http://harvesthq.github.com/chosen/ but I am not sure I want to add more "stuff" to my project. Is there a way to do this with jQuery UI?
Update
I just posted a sample project showcasing the jQueryUI autocomplete on a textbox at GitHub
https://github.com/alfalfastrange/jQueryAutocompleteSample
I use it with regular MVC TextBox like
#Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", #class = "ui-widget TextField_220" })
Here's a clip of my Ajax call
It initially checks its internal cached for the item being searched for, if not found it fires off the Ajax request to my controller action to retrieve matching records
$("#SearchField").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in entityCache) {
response(entityCache[term]);
return;
}
if (entitiesXhr != null) {
entitiesXhr.abort();
}
$.ajax({
url: actionUrl,
data: request,
type: "GET",
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "json",
success: function (data) {
entityCache[term] = term;
response($.map(data, function (item) {
return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode };
}));
}
});
},
minLength: 3,
select: function (event, result) {
var id = result.item.id;
var code = result.item.code;
getEntityXhr(id, code);
}
});
This isn't all the code but you should be able to see here how the cache is search, and then the Ajax call is made, and then what is done with the response. I have a select section so I can do something with the selected value
This is what I did FWIW.
$(document).ready(function () {
$('#CustomerByName').autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
},
});
},
select: function (event, ui) {
$('#CustomerID').val(ui.item.id);
},
minLength: 1
});
});
Works great!
I have seen this issue many times. You can see some of my code that works this out at cascading dropdown loses select items after post
also this link maybe helpful - http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx

Wrong to use AJAX?

I have a view(MVC3) that users place orders from. The view is bound to a model that i use to display modelitems from. There are two functionalities on this view. First you enter the customers details and then you choose the items the user has ordered. This is the code i´m using to build another model to be sent back to serverside:
var modelItems = {
ModelID: [],
Amount: []
};
var serviceModel = {
Name: $.trim($('#name').val()),
Customernumber: $.trim($('#customernumber').val()),
Address1: $.trim($('#address1').val()),
Address2: $.trim($('#address2').val()),
Zipcode: $.trim($('#zipcode').val()),
City: $.trim($('#city').val()),
Country: $.trim($('#country').val()),
Phone: $.trim($('#phone').val()),
Mobile: $.trim($('#mobile').val()),
Email: $.trim($('#email').val())
};
$('div.modelSpan').each(function (i) {
var textBox = $(this).children();
var value = $(textBox).val();
if (value != '0' && value != '') {
var modelID = $(textBox).attr('name');
modelItems.ModelID.push(modelID);
modelItems.Amount.push(value);
}
});
var accessory = {
ModelItems: modelItems,
ServiceModel: serviceModel
};
$.ajax({
url: '/Site/Order', //Renamed sec reasons
type: "POST",
data: JSON.stringify(accessory),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (ordernumber) {
window.location.href = "/Site/OrderInfo/" + businessAB + "/" + ordernumber;
},
error: function () {
alert('error');
}
});
Cool thing in MVC3 is that my accessory automatically binds to my model on serverside called AccessoriesModel. On callback success i´m setting new href to a receipt site to show user what has been created. This all works but my issue is that i would like the receipt view(OrderInfo) to be returned from my controller that receives the [httppost] and not setting new href. Is there a way to do this? This is easy when using regular form submit but because the values for my model dont come from one form it complicates things. Maybe I shouldn´t use AJAX?
You could use knockout JS with Ajax and render your pages with a mixture of JavaScript objects and regular html.

Resources