object doesn't support this property in jquery mvc4 - c#

#Scripts.Render("~/bundles/jquery", "~/bundles/jqueryui", "~/bundles/WorkbenchScripts")
#Styles.Render("~/Content/WorkbenchCss")
<script type="text/javascript">
$(document).ready(function () {
checkSpecialChars('#txtCreateSet');
$('#btnCancelSet').click(function (e) {
window.close();
});
});
//this function is used to allow only specific characters in function
function checkSpecialChars(textboxID) {
debugger;
return textboxID.each
(
function () {
var allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
allowedChars += "abcdefghijklmnopqrstuvwxyz";
allowedChars += "0123456789";
allowedChars += " "; //Space
//Check if try to specifying allowed special characters for Name fields
allowedChars += "-_";
//on keypress
$(textboxID).keypress(function (e) {
var keyUniCode = !e.charCode ? e.which : e.charCode;
var charValue = String.fromCharCode(keyUniCode);
if (keyUniCode != 13) {
if (allowedChars.indexOf(charValue) == -1)
e.preventDefault();
}
});
//On paste
$(textboxID).bind('paste', function (e) {
setTimeout(function () {
var newText = textboxID.val();
$.each(newText, function (i) {
if (allowedChars.indexOf(newText.charAt(i)) == -1)
{ textboxID.val(textboxID.val().replace(newText.charAt(i), '')); }
});
}, 1);
});
}
);
};
</script>
<table>
<tr>
<td>
#Html.Label("Create Set")
</td>
<td>
#Html.TextBoxFor(model => model.SetName, new { id = "txtCreateSet" })
</td>
</tr>
<table>
In the above code i am getting the error "object does not support this property",i am using MVC4 and here i have written the code in mvc view that in the textbox only characters allowed are 0-9 a-z A-Z - _ and space characters.Where i am doing wrong?can anyone help me to get the desired solution?

That's because you're passing your function the selector string and not the objects.
See here:
checkSpecialChars('#txtCreateSet');
That means that when you do the following, you will get that error because there's no each method on a string:
return textboxID.each
Try this, passing the jQuery object:
checkSpecialChars($('#txtCreateSet'));

Related

Get ViewData in View JQuery

I have a Generic List and I'm passing it as ViewData from my Controller to my .aspx View.
I need to get and iterate it with a Jquery Script.
How could I make this script works?
Regards
success: function (result) {
var myArray = new Array();
var myArray = '<%: ViewData["List"] %>';
for (var i = 0; i < myArray.length; i++) {
alert(i);
}
You can do something like this..
<script type="text/javascript">
#{ List<string> ss = (List<string>)ViewData["List"];}
var myArray = [
#for (int i = 0; i < ss.Count; i++)
{
#: #(ss[i]),
}
]
</script>
my syntax for razor view(you can do it for classic)
Try like this , push items of list view to the array of javascript, wrap below code in script tag
--script tag--
var jList = new Array();
#foreach (var item in ViewData["List"] as List<String>)
{
#:jList.push('#item'); // That will work if its a one letter string but It doesnt know that its a string untill you use ''
}
--script tag--
Ok if you are using just a list of strings then
this will do
$(document).ready(function () {
#{List<string> listFromController = (List<string>)ViewData["List"];}
var myArray = [
#for (int i = 0; i < listFromController.Count; i++)
{
#: '#(listFromController[i])',
}
]
});
But if you are passing list of another type rather than string like an student Employee or a user you will need the following
Please use the appropriate class that you have passed and the
properties suppose "UserName" could be "FirstName" "EmpId" or what ever
$(document).ready(function () {
#{ var listFromController = (List<KnockoutJSWebApi.Models.LoginViewModel>)ViewData["list"];}
var totalArray = [];
#for (int i = 0; i < listFromController.Count; i++)
{
<text>
var thisArray= {
'username': '#(listFromController[i].UserName)',
'password': '#(listFromController[i].Password)'
};
totalArray.push(thisArray);
</text>
}
});
Aspx View Engine syntax:
<script>
$(document).ready(function () {
<% List<string> listFromController = (List<string>)ViewData["List"]; %>
var myArray = [
<% for (int i = 0; i < listFromController.Count; i++){ %>
'<%: listFromController[i] %>',
<% } %>
]
debugger;
});
</script>
Problem solved.
I used a JsonResult method in my Controller and returned the needed values as:
Json(List, JsonRequestBehavior.AllowGet);
With that, I don't need to iterate the values because I assign them as datasource to my DropDownList control.
$("#Generic_FK").data("DropDownList").dataSource.data(result);
Hope to help other people with the same issue!
Server Side
public class users
{
public string name{ get; set; }
}
// in your controller code
ViewData["list"] = new List<users>(new users[] { new users()
{ name="prasad"}, new users() {name="raja"}});
Client Side
<script type="text/javascript">
$(function(){
var myitems=JSON.parse('#Html.Raw(Json.Encode(this.ViewData["list"]))');
$.each(myitems, function(index, item) {
var name = item.name;
});
});
</script>
i hope this may help you

Flash Messages in MVC

I was trying to use flash messages in my MVC project, following these instructions:
http://10consulting.com/2011/08/29/asp-dot-net-mvc-flash-messages-with-razor-view-engine/
https://gist.github.com/13orno/d44d0117f17bcd9d0cb7
I added the package Install-Package FlashMessageExtension by the nuget, and were created some items:
FlashMessageExtensions.cs;
_Flash.cshtml;
jquery.flashmessage.js;
jquery.cookie.js;
And as the instructions said, I added it into my _Layout.cshtml:
<script src="#Url.Content("~/Scripts/jquery.cookie.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.flashmessage.js")"></script>
#Html.Partial("_Flash")
In my controller I'm calling:
using MyProject.Extensions;
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name")] Model model)
{
if (ModelState.IsValid)
{
db.Model.Add(model);
db.SaveChanges();
return RedirectToAction("Index").Success("Create was successful");
}
return View(model);
}
For some reason it isn't working, can someone help me?
ERRORS
SCRIPT5009: 'jQuery' is not defined
jquery.cookie.js, line 60 Character 1
Line: jQuery.cookie = function (key, value, options) {
SCRIPT5009: '$' is not defined
jquery.cookie.js, line 1 Character 1
Line: $.fn.flashMessage = function (options) {
SCRIPT5009: '$' is not defined
Create, line 149 Character 5
Line: $("#flash-messages").flashMessage();
Generated Codes:
jquery.cookie.js
jQuery.cookie = function (key, value, options) {
// key and at least value given, set cookie...
if (arguments.length > 1 && String(value) !== "[object Object]") {
options = jQuery.extend({}, options);
if (value === null || value === undefined) {
options.expires = -1;
}
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
value = String(value);
return (document.cookie = [
encodeURIComponent(key), '=',
options.raw ? value : encodeURIComponent(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// key and possibly options given, get cookie...
options = value || {};
var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
jquery.flashmessage.js
$.fn.flashMessage = function (options) {
var target = this;
options = $.extend({}, options, { timeout: 5000, alert: 'alert-info' });
if (!options.message) {
setFlashMessageFromCookie(options);
}
if (options.message) {
var alertType = options.alert.toString().toLowerCase();
if(alertType === "error") {
alertType = "danger";
}
$(target).addClass('alert-' + alertType);
if (typeof options.message === "string") {
$('p', target).html("<span>" + options.message + "</span>");
} else {
target.empty().append(options.message);
}
} else {
return;
}
if (target.children().length === 0) return;
target.fadeIn().one("click", function () {
$(this).fadeOut();
});
if (options.timeout > 0) {
setTimeout(function () { target.fadeOut(); }, options.timeout);
}
return this;
_Flash.cshtml
<script type="text/javascript">
$(function () {
$("#flash-messages").flashMessage();
});
$(document).ajaxComplete(function () {
$("#flash-messages").flashMessage();
});
</script>
You need to include jQuery as well as the flash message scripts:
<script src="#Url.Content("~/Scripts/jquery.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.cookie.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.flashmessage.js")"></script>
It should have downloaded jQuery with it and make sure jQuery is always loaded before all of the other scripts.

value of jquery with autoNumeric textbox into c#

I have 4 textboxes, in 3 of them can numbers be insert and the 4th will output the sum.
Now I'm trying to get the sum to c# as an integer, so I try it with an hidden field "HF_ProjekteGK".
This is my jquery code:
<script src="Scripts/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="Scripts/autoNumeric.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#<%= TB_ProjekteGK.ClientID%>').autoNumeric({ aSep: '.', aDec: ',', aSign: ' €', pSign: 's', aPad: false });
$('#<%= TB_ProjekteAK.ClientID%>').autoNumeric({ aSep: '.', aDec: ',', aSign: ' €', pSign: 's', aPad: false });
$('#<%= TB_ProjekteMAE.ClientID%>').autoNumeric({ aSep: '.', aDec: ',', aSign: ' €', pSign: 's', aPad: false });
$('input:text[id$=TB_ProjekteSumme]').autoNumeric('init', { aSep: '.', aDec: ',', aSign: ' €', pSign: 's', aPad: false });
});
</script>
<script type="text/javascript">
$(function () {
var textBox1 = $('input:text[id$=TB_ProjekteGK]').keyup(projekte);
var textBox2 = $('input:text[id$=TB_ProjekteAK]').keyup(projekte);
var textBox3 = $('input:text[id$=TB_ProjekteMAE]').keyup(projekte);
function projekte() {
var value1 = textBox1.autoNumeric('get');
var value2 = textBox2.autoNumeric('get');
var value3 = textBox3.autoNumeric('get');
var projekte = add(value1, value2, value3);
$('input:text[id$=TB_ProjekteSumme]').autoNumeric('set', projekte);
$("#HF_ProjekteGK").val(projekte);
}
function add() {
var sum = 0;
for (var i = 0, j = arguments.length; i < j; i++) {
if (IsNumeric(arguments[i])) { sum += parseFloat(arguments[i]); }
}
return sum;
}
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
});
</script>
This runs and $("HF_ProjekteGK").val(gesamtsumme); shows the right sum.
Now I'm trying to catch the value to the hidden field:
protected void Button1_Click(object sender, EventArgs e)
{
int test = Convert.ToInt32(HF_ProjekteGK.Value);
}
Here I get an exception that the input string has no correct format becaue it is null. How can I fix this? Thanks!

C# ASP.NET MVC Project and Google Maps: How to fill JavaScript array with values from C# List<>

I have a Class like this:
public class Markers
{
public double latitude { get; set; }
public double longitude { get; set; }
//Constructors and Methods
//(...)
}
On my Controller I have an ActionResult with a List of Markers and I add latitude and longitude like this
List<Markers> listM = new List<Markers>(); //NOTE: this is outside of my ActionResult, no problem with that.
//(...)
listM.Add(new Markers(value[0], value[1])); //NOTE: value[0] is my lat and value[1] is my longitude
//(...)
And at the end i return my list to the View:
return (listM);
Now on the View, I need to access the data and fill an array so I can display the markers on my google map.
How to fill the array with markers in position lat, long from my list?
#using ProjectName.Models
#model List<Markers>
<html>
<head>...</head>
<body>...</body>
<script type="text/javascript">
//How can I add a GoogleMap Marker ?
var markersArray = [];
#foreach(var item in Model)
{
//can't use google.maps.Marker inside this foreach =(
}
</script>
</html>
NOTE: This is how I add a marker on that array with a click on the map.
function addMarker(location) {
var marker = new google.maps.Marker({
draggable: true,
animation: google.maps.Animation.DROP,
position: location,
title: 'Bomb',
map: map,
icon: bomb
});
markersArray.push(marker);
}
Question 2:
Markers still doesn't show on map after #Leo Solution!
<script type="text/javascript">
var map;
var geocoder;
var markersArray = [];
var geoMarker;
var bomb = new google.maps.MarkerImage('Content/Images/Pins/bomb.png',
new google.maps.Size(32, 37),
new google.maps.Point(0, 0),
new google.maps.Point(22, 44)
);
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(41.287739, -7.738992),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
#foreach(var item in Model)
{
<text>
var locations = google.maps.LatLng('#item.latitude', '#item.longitude', false);
addMarker(locations);
</text>
}
geocoder = new google.maps.Geocoder();
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(map);
}
geoMarker = new GeolocationMarker(map);
geoMarker.setCircleOptions({ fillColor: '#808080' });
google.maps.event.addListenerOnce(geoMarker, 'position_changed', function () {
map.setCenter(this.getPosition());
map.fitBounds(this.getBounds());
});
google.maps.event.addListener(geoMarker, 'geolocation_error', function (e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
geoMarker.setMap(map);
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addListener(map, 'click', function (event) {
addMarker(event.latLng);
});
google.maps.event.addListener(map, 'zoom_changed', function () {
var zoomLevel = map.getZoom();
//map.setCenter(myLatLng);
document.getElementById('mapzoom').innerHTML = 'Zoom: ' + zoomLevel;
});
}
function showAddress() {
alert("Vai navegar para outro endereço!");
var address = document.getElementById('txtAddress').value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: mp,
position: results[0].geometry.location
});
} else {
alert('error: ' + status);
}
});
}
function addMarker(location) {
var marker = new google.maps.Marker({
draggable: true,
animation: google.maps.Animation.DROP,
position: location,
title: 'Bomba',
map: map,
icon: bomb
});
markersArray.push(marker);
}
function setAllMap(map) {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(map);
}
}
function clearMarkers() {
setAllMap(null);
}
function showMarkers() {
setAllMap(map);
}
function deleteMarkers() {
clearMarkers();
markersArray = [];
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' +
'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
if (!navigator.geolocation) {
alert('Your browser does not support geolocation');
}
</script>
Try this.....
<script>
var markersArray = [];
var _map = null;
var _c = null;
#foreach(var item in Model)
{
<text>
markersArray.push(new google.maps.Marker({
draggable: true,
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng('#item.latitude', '#item.longitude', false),
title: 'Whatever title',
map: _map
}));
</text>
}
</script>
Second Question
I had to carefully look at your code and found 3 problems...one of them you've already mentioned it. The other ones are that you are duplicating variable names and you are not instantiating a new object. Now change this....
#foreach(var item in Model)
{
<text>
var locations = google.maps.LatLng('#item.latitude', '#item.longitude', false);
addMarker(locations);
</text>
}
to this....
#foreach(var item in Model)
{
<text>
addMarker(new google.maps.LatLng(parseFloat('#item.latitude'), parseFloat('#item.longitude')));
</text>
}
Let me know how it goes

pass javascript message to csharp

I have a javascript code that works wonderfully:
<script type="text/javascript">
var maxWords = 100;
function limitLengthInWords(field)
{
var value = field.value,
wordCount = value.split(/\S+/).length - 1,
re = new RegExp("^\\s*\\S+(?:\\s+\\S+){0," + (maxWords - 1) + "}");
if (wordCount >= maxWords)
{
field.value = value.match(re);
alert("Max reached");
}
document.getElementById(field).innerHTML = maxWords - wordCount;
}
</script>
how do i replaced the alert("Max reached") so that it shows the validation message for the textarea that i am checking:
#Html.ValidationMessageFor(model => model.description)
can i do this:
<script type="text/javascript">
var maxWords = 100;
function limitLengthInWords(field)
{
var value = field.value,
wordCount = value.split(/\S+/).length - 1,
re = new RegExp("^\\s*\\S+(?:\\s+\\S+){0," + (maxWords - 1) + "}");
if (wordCount >= maxWords)
{
field.value = value.match(re);
#Html.ValidationMessageFor(field,"Max reached");
}
document.getElementById(field).innerHTML = maxWords - wordCount;
}
</script>
The easiest way would be to have a some hidden text that you show.
<span style="display:none;" class="max-reached">Max Reached</span>
$(".max-reached").show()
Alternatively try using a library that does this and includes a countdown. Such as NobleCount
Make sure you have your model annotated correctly, i am using password property as an example
[StringLength(30, ErrorMessage = "Error Message")]
public string Password
{
get;
set;
}
Change this #Html.ValidationMessageFor(field,"Max reached");
to I am assuming $(field) is the id such as $('#Password') all you have to do is access the data information stored by mvc $(field).data('val-length')

Categories