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')
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 have display for my data like
#Html.DisplayFor(m=> m.UserName)
Result
John
I want to show only one character and hide the rest for user name data.
Result that is required
J######
Is there a quick way to display something like this, or will I have to write my own backend logic?
You can try to put #Html.DisplayFor(m=> m.UserName) into div;
and change the content of div with $(function(){}):
<div id="UserName">#Html.DisplayFor(m => m.UserName)</div>
<script>
$(function () {
var userName = document.getElementById('UserName').innerHTML;
var characters = userName.split('');
var newUserName = "";
if (characters.length > 0) {
newUserName = characters[0];
for (var i = 1; i < characters.length; i++) {
newUserName += '#';
}
}
document.getElementById('UserName').innerHTML = newUserName;
})
</script>
I have a list in Razor Page which i want to use in java script.I'm using viewdata to send data to view VIewbag is working for some reason in razor page.
I'm using .net core 2.2
Things i already tried.
View
Things i already tried:
var a=#Model.listname
var stringArray = #Html.Raw (Json.Serialize(ViewData["Quest"]));` viewdata[Quest] contains list
string jsonn = JsonConvert.SerializeObject(quelist);`
and then send jsoon to view.
using custom class object and create create json object using Newtonsoft.Json and send to view
If you proposing ajex solution explain it a little as i dont know much about it or share a link for explanation
Razor page .cs file Commented the things that didn't
public async Task OnGetAsync()
{
ViewData["opt1"] = o1list;
ViewData["quest"] = quelist;
// string jsonn = JsonConvert.SerializeObject(quelist);
// ViewData["Jon"] = jsonn;
QuestionBank = await _context.QuestionBank
.Include(q => q.QuestionLevel)
.Include(q => q.QuestionStyle)
.Include(q => q.Teacher)
.Include(q => q.Topic).ToListAsync();
Answer = await _context.Answer.ToListAsync();
QSID = await _context.QSID.ToListAsync();
View
#{var name = (List<String>)ViewData["Quest"]; }
<script>
/*function test() {
var array = #Html.Raw(Json.Serialize(ViewData["Jon"]));
for(var i = 0; i < array.length; i++) {
alert(array[i]);
console.log(array[i]);
}
}
test();
*/</script>
</head>
<body>
#{
Model.run();
var name = (List<String>)ViewData["Quest"];
var nam = (List<String>)ViewData["opt1"];
int j = 0;
for (int i = 0; i <= 4; i++)
{
var a = name[i];
<p > #a </p>
<form action="">
<input type="radio" name="s" value="">#nam[j]<br>
#{j = j + 1; }
<input type="radio" name="s" value="">#nam[j]<br>
#{j = j + 1; }
<input type="radio" name="s" value="">#nam[j]<br>
#{j = j + 1; }
<input type="radio" name="s" value="">#nam[j]
#{j = j + 1; }
</form>
}
}
I expect to get a array containing my list or in json format
This is how I do it in a project I created:
<script>
var saleTypesById = #Html.Raw(JsonConvert.SerializeObject(Model.TypesById));
</script>
Where Model.TypesById is a Dictionary<long,SaleType>.
To use from javascript I call:
var selectedSaleType = saleTypesById[selectedId];
Then I can just call properties on it like selectedSaleType.Comission
This code requires #using Newtonsoft.Json; directive and a reference to the corresponding nugget package.
I follow the above example but with an extra step:
<script type="text/javascript">
window.onload = function () {
try {
var movsArray = '#Html.Raw(JsonConvert.SerializeObject(Model))';
var opt = JSON.parse(movsArray);//Extra step
if (opt.length > 0) {
//You can use opt as array of objects
}
} catch (Error) {
console.log("Error");
}
};
</script>
or maybe you can use a loop instead of if
<script type="text/javascript">
window.onload = function () {
try {
var movsArray = '#Html.Raw(JsonConvert.SerializeObject(Model))';
var opt = JSON.parse(movsArray); //Extra step
for(var i = 0;i<opt.length;i++){
//you can use opt[i] as object, example opt[i].id
}
} catch (Error) {
console.log("Error");
}
};
</script>
Where Model is List<Mov_Tipo>
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.
Hello i want to use counter which takes value from js file, but i want to change it.
Here is js code;
function countUp(count)
{
var div_by = 100,
speed = Math.round(count / div_by),
$display = $('.count'),
run_count = 1,
int_speed = 24;
var int = setInterval(function() {
if(run_count < div_by){
$display.text(speed * run_count);
run_count++;
} else if(parseInt($display.text()) < count) {
var curr_count = parseInt($display.text()) + 1;
$display.text(curr_count);
} else {
clearInterval(int);
}
}, int_speed);
}
countUp(600);
It counts to 600 but i want assign variable to this from database probly with codebehind.
Here is html code ;
<div class="col-lg-3 col-sm-6">
<section class="panel">
<div class="symbol red">
<i class=" fa fa-times text-muted"></i>
</div>
<div class="value">
<h1 class="count">123123123</h1>
<p>Position Canceled</p>
</div>
</section>
</div>
How can i change countUp value in js. Please help me.
Thank You
function countUp(count)
{
var div_by = 100,
speed = Math.round(count / div_by),
$display = $('.count'),
run_count = 1,
int_speed = 24;
var int = setInterval(function() {
if(run_count < div_by){
$display.text(speed * run_count);
run_count++;
} else if(parseInt($display.text()) < count) {
var curr_count = parseInt($display.text()) + 1;
$display.text(curr_count);
} else {
clearInterval(int);
}
}, int_speed);
}
var _count=0;
//If you are retreiving count from database, you can perform ajax call
var request = $.ajax({
url: url,
type: "GET",
dataType: json
});
request.done(function(msg) {
_count=msg.data;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
//if you are assinging count value from html tags
eg: assign value into hidden field, then
<input type="hidden" id="count" value="600"/>
_count=$('#count).val();
countUp(600);
You can use following syntax:
countUp('<%= CountValueFromDB %>');
Where CountValueFromDB is variable you can declare in your code-behind for particular page and populate it from database or any other source in your Page_Load method or another method called during page life cycle.
Alternatively you can call RegisterStartupScript in your code behind passing "countUp(" + CountValueFromDB + ");" for 'script' parameter.