Client-side validation against an object in ASP.Net-MVC3? - c#

I have ah HTML5 form with an action defined as follows:
#using (Html.BeginForm("SearchAction", "ResultsController"))
The form takes in two text fields:
<input type="text" name="txtSearchTerm" id="txtSearchTerm" class="frontPageInput" placeholder="Begin your search..." required />
<input type="text" name="txtGeoLocation" id="txtGeoLocation" class="frontPageInput" required />
The txtGeoLocation field is an autocomplete field that is fed from a cached object, fed through the controller and by a model repository class through the following jQuery code:
<script type="text/javascript" language="javascript">
$(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;
}
});
});
There's an alert there for debugging. When clicking on the text that drops down, this alert fires, however it does not fire if you type in the whole word and hit submit.
I would like to first, validate the text in the geo text box on the client side, to ensure that it is a value contained in the collection, of not, have the text box in red, communicate that.
Thanks.

You can use jquery remote validation using the [Remote()] attribute to validate the value is in the list. You will have to do the same check on the server side when you post back as well.

Related

How to refresh a particular division while using MVC

I have tried different ways to refresh a particular division in MVC.
1. Using HTML Action Link
2. Ajax Action Link
3. method
Please help me resolve this issue.
My Code is as follows:
<script src="~/scripts/jquery.unobtrusive-ajax.js"></script>
<script>
function updateAsyncCategoryUpdate() {
var url = '/Home/HomePage';
$.ajax({
url: url,
//data: { value: '1234' }, //if there are any parameters
dataType: "html", //or some other type
success: function () {
window.location.reload(true);
// or something in that area, maybe with the 'data'
},
error: function () {
//some derp
}
});
}
</script>`
#Ajax.ActionLink(item.Name, "HomePage", new { CATEGORy = item.Name }, new AjaxOptions {HttpMethod="GET", OnSuccess = "updateAsyncCategoryUpdate('item.Name')" })
You can append the success function.
This replaces content of div
success: function (data)
{
$('#divSelector').html(data);
}
This appends content of div
success: function (data)
{
$('#divSelector').append(data);
}
Your script function does not have parameter and you send Item.Name to it.(although you dont use this parameter inside the script!)
First, define parameter for updateAsyncCategoryUpdate function.
Secomd,Add a container element(like div) to your page with specific id(resultDiv for example) and replace the success code of your scrip with this:
success: function(result){
var myDiv = $('#resultDiv');
myDiv.empty();
myDiv.prepend(result);
}

Pass Option Select Value to Controller

im trying to get the value each time a client selects a option from my Dropdown list to send it back to controller where i use the value on creating a file and then refreshing the page but im unable to do so
This is my Dropdownlist:
<select id="sel0">
<option value="">Todos</option>
#foreach (var item in Model.Select(l => l.Fecha).Distinct())
{
<option value="#lines">#lines</option>
}
</select>
This is my Ajax Call:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
});
$("form").submit(function () {
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
and this is my Controller its named 'HomePosController':
public ActionResult MethodName(string Selected)
{
var db = new ArponClientPosContext();
String value = Selected;
var json4 = JsonConvert.SerializeObject(Selected);
System.IO.File.WriteAllText(#"C:\inetpub\wwwroot\potzolcalli.brain.arpon.com\valorselected.txt", json4);
return View("~/Views/HomePos/Index.cshtml", db.Pos.ToList());
}
But whenever y select a option of my dropdown nothing happens, the page its not refreshed nor the file is created what am i doing wrong?
If you want it to be on dropdown change then you have to send ajax call in change event :
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePos")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
and you have to not write complete Controller class name, you have to skip the Controller postfix, it is convention which is followed by Url helpers in mvc, that way your url generated will be wrong and ajax call will fail.
whenever y select a option of my dropdown nothing happens
Well, this happens:
dataTable.columns('.fechas').search(this.value).draw();
But that doesn't invoke the AJAX request. It doesn't do much of anything, really.
how can i trigger the ajax ? i want it to trigger after a value is changed in the dropdown list
In that case you want to do that on the select element's change event. Currently you perform the AJAX request here:
$("form").submit(function () {
// AJAX
});
That is, you perform the request in the form's submit event. Just add it to the drop down's change event instead:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
the page its not refreshed
Well, no. That won't happen in an AJAX request. Currently your success callback is empty, so nothing will happen on the page. Whatever you want to happen would need to be put in that callback.

Auto Complete in Razor MVC.NET [duplicate]

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

Ajax respond is not reflected into pop-up view

I have created a button to pass some parameters to a controller and get the response in a responsive pop-up.
But somehow when I click the button, nothing happens. No error in Dev.Option (F12), and I already make sure the parameter goes into my controller.
My reference : http://aspsnippets.com/Articles/Open-Show-jQuery-Dialog-Modal-Popup-after-AJAX-Call-Success.aspx
I'm using MVC C# on Visual Studio 2010. Below is my code:
My home page, all pre-requisite Jquery are already automatically reloaded inside global.asax.
HomePage.cshtml
var externalID = "123";
var susbcrNo = "456";
<a href="#COV" onclick="javascript:CustomerOneView.displayPopUpWindow(#externalID, #susbcrNo);" >DETAILS</a>
<div id="dialog" style="display: none"/>
#section Scripts{
<script type="text/javascript" src="#Url.Content("~/Scripts/CustomerOneView.js")" ></script>
<script type="text/javascript">
$("#dialog").dialog({
autoOpen: false,
modal: true,
title: "Details",
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
Inside CustomerOneView.js :
var CustomerOneView = (function () {
return {
init: function () {
},
displayPopUpWindow: function (externalID, susbcrNo) {
var postData = {
externalID: externalID,
susbcrNo: susbcrNo
};
$.ajax({
type: "POST",
url: "/Home/OneViewDetails",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
$("#dialog").html(r);
$("#dialog").dialog("open");
}
});
}
};
})();
$(document).ready(function () {
CustomerOneView.init();
});
My controller :
[HttpPost]
public JsonResult OneViewDetails(string externalID, string susbcrNo)
{
Models deviceDetails = new Models();
deviceDetails.Code = externalID;
deviceDetails.Message = susbcrNo;
// call log here make sure the values.
Logger.Debug("COV called here " + externalID + " - " + susbcrNo);
// old return
// return Json(deviceDetails, JsonRequestBehavior.DenyGet);
return Json(deviceDetails);
}
My Controller is already tied into a view that supposed to be a pop-up view. Let's call it PopUp.cshtml
How can I fix this issue?
I need to clarify something about C# on the server side; if you return a value on a function/method, it will return the value to the code that called said function/method as opposed to intelligently guessing that you want to print the value back to the client so the browser may then manipulate the results?
If that is the case, you need to echo or print the return value from the function/method or from where the function/method is called.

jquery ui tab not posting data to asp.net(c#)

The HTML for jqueryUI tabs.
<div id="lodg_tabs" class="tabs">
<ul>
<li>Add/Remove</li>
<li>Update</li>
</ul>
<div id="tabs-1" class="forms">
<h3 align="center">Mandate Lodgment</h3>
<form name="mand_lodg" id="mand_lodg" method="post">
ajax code to send parameters to the tab loading "mand_lodg_upd.aspx"
$("#lodg_tabs").tabs({
select: function (event, ui) {
var res = valid('mand_lodg');
$(this).tabs("option", { ajaxOptions: { data: $("#mand_lodg").serialize()} });
},
ajaxOptions: {
type: 'POST',
error: function (xhr, status, index, anchor) {
$(anchor.hash).html("An error has been encountered while attempting to load this tab.");
}
},
cache: false
});
the c# code behind
Response.Write(Request.Form["zone"] + Request.QueryString["zone"]);
zone.Value = Request.Form["zone"];
loc.Value = Request.Form["loc"];
date.Value = Request.Form["date"];
The output: Output is ok, the file is loading in the tab
The problem : but the parameters passed with ajax i.e
$(this).tabs("option", { ajaxOptions: { data: $("#mand_lodg").serialize()} });
zone location and date are null in c# code behind
Request.Form is referring to HTTP request parameters via the POST method. JQuery by default issues a GET method request. Try setting your AJAX Options like so:
$(this).tabs("option", {
ajaxOptions: {
type: 'post',
data: $("#mand_lodg").serialize()
}
});

Categories