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!
Related
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
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.
I can't see the wood for the trees.
Why is this throwing a String Format Exception?
private const string GoogleAnalyticsFormat = #"<script type=""text/javascript"">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '{0}']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>";
public static IHtmlString RenderGoogleAnalytics<T>(this HtmlHelpers<T> html, string trackingCode )
{
return html.Raw(string.Format(GoogleAnalyticsFormat, trackingCode));
}
Look at this bit of your format string:
function () { ... }
Those braces are being interpreted as the start/end of placeholders. You need to double them:
function () {{ ... }}
So your complete declaration would be:
private const string GoogleAnalyticsFormat = #"<script type=""text/javascript"">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '{0}']);
_gaq.push(['_trackPageview']);
(function () {{
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
}})();
</script>";
You have to change braces { to {{
#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'));
my application is MVC4; I am trying to populate a Telerik MVC using json, the result is an array; however I get only one item; here is my script:
function CheckWord() {
var wordtocheck = $('#Cword').val();
alert(wordtocheck);
$.ajax({
url: '/Home/CheckWord',
type: 'POST',
data: {
cword: wordtocheck
},
success: function (data) {
for (var i = 0; i < data.array.length; ++i) {
var myString = data.array[i];
var mySplitResult = myString.split("-->");
var hms = mySplitResult[0];
var a1 = hms.split(',');
var a2 = a1[0];
var a = a2.split(':');
var start = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var hms1 = mySplitResult[1];
var b1 = hms1.split(',');
var b2 = b1[0];
var b = b2.split(':');
var end = (+b[0]) * 60 * 60 + (+b[1]) * 60 + (+b[2]);
var dropDownList = $('#ComboBox').data('tComboBox');
dropDownList.dataBind([
{ Text: start[i] + "-" + end[i], Value: start[i] + "-" + end[i] }]);
dropDownList.select(0);
}
},
error: function () {
}
});
When I add [i] after start and end, I get undefined! without [i] I get the correct value however just one item. Would appreciate your suggestions, thanks in advance.
Hope the following link will help
http://www.telerik.com/community/forums/aspnet-ajax/mvc/radcombobox-populate-on-client-side.aspx
Here you can see
<telerik:RadComboBox ID="radProject" runat="server" Skin="Default" Width="300px"
EnableLoadOnDemand="true" Filter="Contains" OnClientItemsRequesting="getProjects"
EmptyMessage="Select Project" />
in the above code EnableLoadOnDemand is set to true and Filter is set to contains and the event bound to OnClientItemsRequesting.
function getProjects(sender, args) {
itemsRequesting(sender, args);
$.getJSON(
'<%= Url.Action("GetProjects", "Capital") %>',
{ facility: GetFacility().get_value() },
function(data) {
fillCombo(sender, data);
sender.highlightAllMatches(sender.get_text());
});
}
the above javascript method is executing a ajax call using get JSON with parameters and the sub methods fillCombo is filling the combo box.
// Use this for all of your RadComboBox to populate from JQuery
function fillCombo(combo, result) {
combo.clearItems();
var items = result.d || result;
// This just lets your users know that nothing was returned with their search
if (items.length == 0) {
var comboItem = new Telerik.Web.UI.RadComboBoxItem();
comboItem.set_text("Nothing found");
comboItem.set_value("null");
combo.get_items().add(comboItem);
combo.set_text("");
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
var comboItem = new Telerik.Web.UI.RadComboBoxItem();
comboItem.set_text(item.Text);
comboItem.set_value(item.Value);
combo.get_items().add(comboItem);
}
}
Now in order to cancel the default behavious of RADComboBox you can use the following code
// This cancels the default RadComboBox behavior
function itemsRequesting(sender, args) {
if (args.set_cancel != null) {
args.set_cancel(true);
}
if (sender.get_emptyMessage() == sender.get_text())
sender.set_text("");
}
I hope the above solution will solve your problem
Here is how I solved the problem:
function CheckWord() {
var wordtocheck = $('#Cword').val();
alert(wordtocheck);
$.ajax({
url: '/Home/CheckWord',
type: 'POST',
data: {
cword: wordtocheck
},
success: function (data) {
var listData = [];
for (var i = 0; i < data.array.length; ++i) {
var myString = data.array[i];
var mySplitResult = myString.split("-->");
var hms = mySplitResult[0];
var a1 = hms.split(',');
var a2 = a1[0];
var a = a2.split(':');
var start = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var hms1 = mySplitResult[1];
var b1 = hms1.split(',');
var b2 = b1[0];
var b = b2.split(':');
var end = (+b[0]) * 60 * 60 + (+b[1]) * 60 + (+b[2]);
listData[i] = { Text: myString, Value: start };
}
var dropDownList = $('#ComboBox').data('tComboBox');
// debugger;
dropDownList.dataBind(listData);
dropDownList.select(0);
},
error: function () {
}
});
}
Hope this will be helpful to others.