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.
Related
Is it possible to show the remaining session time in View in real-time when logged in ASP.NET MVC project? I didn't add any code to the question because I didn't come across any solution during my research.
I would do this in 2 steps, first pass the timeout value using a partial, so it can be reused. For e.g. read it from your Web.Config etc and pass it.
Then inside your view, you can add this script and adapt/modify the values.
#functions {
public int PopupShowDelay {
get { return 60000 * (Session.Timeout - 1); }
}
}
<script type="text/javascript">
window.SessionTimeout = (function() {
var _timeLeft, _popupTimer, _countDownTimer;
var stopTimers = function() {
window.clearTimeout(_popupTimer);
window.clearTimeout(_countDownTimer);
};
var updateCountDown = function() {
var min = Math.floor(_timeLeft / 60);
var sec = _timeLeft % 60;
if(sec < 10)
sec = "0" + sec;
document.getElementById("CountDownHolder").innerHTML = min + ":" + sec;
if(_timeLeft > 0) {
_timeLeft--;
_countDownTimer = window.setTimeout(updateCountDown, 1000);
} else {
window.location = "Home/TimeOutPage";
}
};
var showPopup = function() {
_timeLeft = 60;
updateCountDown();
ClientTimeoutPopup.Show();
};
var schedulePopup = function() {
stopTimers();
_popupTimer = window.setTimeout(showPopup, #PopupShowDelay);
};
var sendKeepAlive = function() {
stopTimers();
ClientTimeoutPopup.Hide();
SessionTimeout.schedulePopup();
};
return {
schedulePopup: schedulePopup,
sendKeepAlive: sendKeepAlive
};
})();
</script>
#using (Html.BeginForm()) {
<p>
A timeout warning popup will be shown every #(Session.Timeout - 1) min.
</p>
#Html.Partial("TimeoutPartial")
}
i try to get a time from Ajax request dateType json .
the result i get is :
/DATE(1436688000000)/
heres my code :
view:
<div class="col-sm-8">
#Html.DropDownListFor(model => model[i].MovieShowTime.Single().MovieID, SelectMovieID, "Select Movie", new { id = "MovieName", name = "MovieName" })
#Html.DropDownListFor(x => x[i].MovieShowTimeID, Enumerable.Empty<SelectListItem>(), "--Loading Value--", new { id = "ShowTime", name = "ShowTime" })
#Html.ValidationMessageFor(model=>model[i].MovieShowTimeID)
</div>
controller :
public JsonResult GetShowTime(int? MovieID)
{
var data = (from m in db.MovieShowTimes
where m.MovieID == MovieID
select new
{
id = m.MovieShowTimeID,
name = m.ShowTime
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
ajax : .
$(function () {
$('#MovieName').change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("GetShowTime", "TimeScreening")',
data: { MovieID: $('#MovieName').val() },
dataType : 'json',
success: function (data) {
$('#ShowTime').html('');
//alert(ChangeDateFormat("\/Date(1319266795390+0800)\/"));
$.each(data, function (id, option) {
var name = ChangeDateFormat(option.name)
$('#ShowTime').append($('<option></option>').val(option.id).html(option.name));
});
},
error: function (xhr, ajaxOptions, thrownEror) {
alert("False" + xhr +"..."+ ajaxOptions +"... "+ thrownEror);
}
});
});
});
i see the threds about convert form json to C# datetime but none of them have resolved the problem .
follow by this post:
JSON-Serialization-and-Deserialization-in-ASP-NET this jave me the closet answer , but this in date.
code:
function ChangeDateFormat(jsondate) {
jsondate = jsondate.replace("/Date(", "").replace(")/", "");
if (jsondate.indexOf("+") > 0) {
jsondate = jsondate.substring(0, jsondate.indexOf("+"));
}
else if (jsondate.indexOf("-") > 0) {
jsondate = jsondate.substring(0, jsondate.indexOf("-"));
}
var date = new Date(parseInt(jsondate, 10));
var month = date.getMonth() + 1 < 10 ?
"0" + (date.getMonth() + 1) : date.getMonth() + 1;
var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return date.getFullYear() + "-" + month + "-" + currentDate;
}
this answer : Format a Microsoft JSON date really no ugly parsing but this gave me a datetime.now and no close to time.
this answer : ASP.NET MVC JsonResult Date Format is the same.
and this artical is good but the same.. dates-and-json
so.. what i need to do?
I have this set of functions
// START Datetime Converters
function DateConverter(date) {
var aux = null;
if (date != null) {
aux = date.substring(6);
aux = aux.substring(0, aux.indexOf(')'));
}
return aux != null ? getISODate(new Date(parseInt(aux))) : "";
}
function DatetimeConverter(date) {
var aux = null;
if (date != null) {
aux = date.substring(6);
aux = aux.substring(0, aux.indexOf(')'));
}
return aux != null ? getISODateTime(new Date(parseInt(aux))) : "";
}
function getISODate(d) {
// padding function
var s = function (a, b) { return (1e15 + a + "").slice(-b) };
// default date parameter
if (typeof d === 'undefined') {
d = new Date();
};
// return ISO datetime
return zeroPad(d.getDate(), 2) + '/' +
zeroPad(s(d.getMonth() + 1, 2), 2) + '/' +
zeroPad(d.getFullYear(), 4);
}
function getISODateTime(d) {
// padding function
var s = function (a, b) { return (1e15 + a + "").slice(-b) };
// default date parameter
if (typeof d === 'undefined') {
d = new Date();
};
// return ISO datetime
return zeroPad(d.getDate(), 2) + '/' +
zeroPad(s(d.getMonth() + 1, 2), 2) + '/' +
zeroPad(d.getFullYear(), 4) + " " +
zeroPad(d.getHours(), 2) + ":" +
zeroPad(d.getMinutes(), 2) + ":" +
zeroPad(d.getSeconds(), 2);
}
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
// END Datetime Converters
Example: In a table where i show the CreatedDate:
{
"mRender": function (oAux, oType, oData) {
return DateConverter(oData.CreatedDate);
},
},
If you want Date and Time just use DatetimeConverter
What i'm doing
Inside the function DateConverter and DateTimeConverter i catch the number without the \DATE... like "1436688000000".
Then inside the getISODate, in the first line:
var s = function (a, b) { return (1e15 + a + "").slice(-b) };
Is a padding function. Where the day 2 will become "02" if you use it like:
s(d.getDate(), 2)
If the date that the action returns is null or invalid:
if (typeof d === 'undefined') {
d = new Date();
};
The other padding function is zeroPad that does what the function s() does but doesn't remove the left numbers, example:
var a = 3000;
var sA = s(3000, 2);
var zpA = zeroPad(3000, 2);
sA will become "00" while zpA will keep "3000"
PS: I can't remember why i used s function... i think that i forgot to delete it after creating zeroPad.
#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.
SuperNoob here, trying to load varying multiple "Options" either as a string[] or object, to a "Product" that can be added to a shopping cart using Knockout: (working from John Papa's PluralSight Knockout Change Tracking example)
Here is the view:
<div>
<span>OptionsArray: </span>
<ul data-bind="foreach: optionsArray">
<li data-bind="text: $data"></li>
</ul>
</div>
Here is the JSON converted into C#:
{Id = 4, ModelId = 1, SalePrice = 1.00, ListPrice = 1.00, Rating = 5, Photo = "smallCoffee.jpg", CategoryId = 1, ItemNumber = "smallCoffee", Description = "Small Coffee", Model = new Model(){ Name = "Small Coffee", Brand = "Tim Hortons", Id = 1 }, Category = drinkCat, Options = new Options(){Name = "Sugar"}, OptionsArray = new string[]{"Sugar", "Cream"}}
This javascript function works, loading json into an "products" array of Products, except I can't get it to iterate through varying multiple options for each product.
Here is the function part of the view model:
loadProductsCallback = function (json) {
my.vm.tracker().markCurrentStateAsClean();
$.each(json, function (i, p) {
products.push(new my.Product(selectedProduct)
.id(p.Id)
.salePrice(p.SalePrice)
.photo(p.Photo)
.category(new my.Category()
.id(p.Category.Id)
.name(p.Category.Name)
)
.model(new my.Model()
.id(p.Model.Id)
.name(p.Model.Name)
.brand(p.Model.Brand)
)
.options(new my.Options()
.name(p.Options.Name)
)
.description(p.Description)
.rating(p.Rating)
.stateHasChanged(false);
$.each(p.OptionsArray, function(i, o) { p.optionsArray.push(o);});
);
});
And here is the Product object that is taking all the data:
Product = function (selectedItem) {
var self = this;
self.id = ko.observable();
self.salePrice = ko.observable();
self.photo = ko.observable();
self.model = ko.observable();
self.options = ko.observable();
self.optionsArray = ko.observableArray(["1", "2"]);
self.category = ko.observable();
self.description = ko.observable();
self.rating = ko.observable();
self.isSelected = ko.computed(function () {
return selectedItem() === self;
});
self.isDrink = ko.computed(function () {
return this.category() ? this.category().id() === 1 : false;
}, self),
self.isFood = ko.computed(function () {
return this.category() ? this.category().id() === 4 : false;
}, self),
self.shortDesc = ko.computed(function () {
return this.model() ? this.model().name() : "";
}, self),
self.opt = ko.computed(function () {
return this.options() ? this.options().name() : "";
}, self),
self.optQty = ko.computed(function () {
return this.options() ? this.options().qty() : "";
}, self),
self.photoUrl = ko.computed(function () {
return photoPath + this.photo();
}, self),
self.rating.subscribe(function () {
this.stateHasChanged(true);
}, self),
self.stateHasChanged = ko.observable(false);
};
The loadProductsCallback function works fine except for the part adding the nested OptionsArray in. I've tried a nested $.each functions and just simply .optionsArray(p.OptionsArray).
There is a lot more code: I hope that this is enough to make sense.
Dear Stackers, how can I properly load the OptionsArray into the Products object using this function?
Not sure I'm quite understanding your code but here goes.
You are new'ing up a product then trying to loop through a collection and map it to options. Except you are pushing the results to the source object.
What about this.
loadProductsCallback = function (json) {
my.vm.tracker().markCurrentStateAsClean();
$.each(json, function (i, p) {
var newProduct = new my.Product(selectedProduct)
.id(p.Id)
.salePrice(p.SalePrice)
.photo(p.Photo)
.category(new my.Category()
.id(p.Category.Id)
.name(p.Category.Name)
)
.model(new my.Model()
.id(p.Model.Id)
.name(p.Model.Name)
.brand(p.Model.Brand)
)
.options(new my.Options()
.name(p.Options.Name)
)
.description(p.Description)
.rating(p.Rating)
.stateHasChanged(false);
$.each(p.OptionsArray, function(i, o) {
newProduct.optionsArray.push(o);
});
products.push(newProduct);
});
}
Hope this helps.