how to add javascript to an Asp.net MVC app - c#

I am building an Asp.net MVC app and would like to add a datepicker.
I have this code in my form in the view
#Html.LabelFor(b => b.Date)
#Html.EditorFor(b => b.Date, new {id = "news_date"})
and I would like to add this javascript to it to enable to datapicker:
$(document).ready(function () {
$("#news_date").datepicker({ dateFormat: 'dd/mm/yy' });
});
however when the application is run it shows the above code as text on the page.
How do I get it to recognize it as javascript?

Use script tag
#Html.LabelFor(b => b.Date)
#Html.EditorFor(b => b.Date, new {id = "news_date"})
<script type="text/javascript">
$(document).ready(function () {
$("#news_date").datepicker({ dateFormat: 'dd/mm/yy' });
});
</script>

wrap your code with script tags
<script type="text/javascript">
$(document).ready(function () {
$("#news_date").datepicker({ dateFormat: 'dd/mm/yy' });
});
</script>

Related

viewmodel parameter into json for ajax request

In my Net Core 2.1 MVC project I have a viewmodel parameter userID, that I want to assign to a JQuery variable after the page loads. The ID is not displayed anywhere on the page.
So far, this doesn't seem to work:
View:
#{int userID = Model.ID;}
// rest of html page.
#section scripts {
<script src="~/AssigntoVariable.js"></script>
}
AssignToVariable.js
$(document).ready(function () {
$(function () {
var json = userID;
console.log(json);
// removed further code
When I run this, I receive a 'UserID not defined' error, obviously.
How can I put the userID parameter from my viewmodel directly in a JQuery script?
You can access viewmodel parameter ID as userID on client-side like:
#section scripts {
<script type="text/javascript">
var userID = #(Html.Raw(Json.Encode(Model.ID)));
// You can now access userID here
console.log(userID);
</script>
<script src="~/AssigntoVariable.js"></script>
}
and now you can also access userID in AssignToVariable.js like:
$(document).ready(function () {
var json = userID;
console.log(json);
});
Please note that you don't need to use
$(document).ready(function () {
$(function () {
both of them in AssignToVariable.js file, as $(function () { is just a shorthand for $(document).ready(function () {. Please use either one of them.

Interference between dropdownlists

In my view I have a code like
<div id="DDLs">
<p>Begin: #Html.DropDownListFor(model => model.ItemID, Model.items, new { #id = "list1" })</p>
</div>
...
<script type="text/javascript">
$(document).ready(function () {
$("#list1").change(function () {
var countrySelected = $("select option:selected").first().text();
$.get('#Url.Action("MyAction")',
{ id: countrySelected }, function (data) {
$("#apendedInfo").html(data);
});
});
});
</script>
That works as expected.The problem is when I add another dropdownlistfor like this:
<div id="DDLs">
<p>Begin: #Html.DropDownListFor(model => model.ItemID, Model.items, new { #id = "list1" })</p>
<p>Options: #Html.DropDownListFor(model => model.Option, #ViewBag.Options as SelectList, new { #id = "list2"})</p>
</div>
After adding it, change event is sometimes fired with selected value of the added dropdownlist, not the one that I expect it would. I have no idea why.
Edit:
Thanks to dansasu11 answer, I've figuired out that the problem was in line:
var countrySelected = $("select option:selected").first().text();
I changed it to:
var countrySelected = $(this).val();
Now everything works - of ocurse insted of reciving Text of selected item I'm getting its value, which is also fine.
Perhaps I should have spent more time learning jQuery.
try
<script type="text/javascript">
$(document).ready(function () {
$("#list1").change(function () {
var countrySelected = $(this).find("option:selected").text();
$.get('#Url.Action("MyAction")',
{ id: countrySelected }, function (data) {
$("#apendedInfo").html(data);
});
});
});
</script>
or if you want to be able to select any of the dropdown and get the selected option then change to
<script type="text/javascript">
$(document).ready(function () {
$("select").change(function () {
var countrySelected = $(this).find("option:selected").text();
$.get('#Url.Action("MyAction")',
{ id: countrySelected }, function (data) {
$("#apendedInfo").html(data);
});
});
});
</script>

JQuery get value from .resx file

When I change my dropdown list, I want change a label (lblCustomer).
I don't know how to get value from resource file.Any ideas!?
.text('"<%$ Resources:lblCustomer%>"'); this not work. 10x
$(function () {
$('#<%= ddlCustomer.ClientID %>').change(function ()
{
$('#<%= lblCustomer.ClientID %>').text('"<%$ Resources:lblCustomer%>"');
})
}
);
I had similar problem to this. What I end up doing is registering a startup script that reads the values from the .resx file into a variable in javascript. Then I just reference the javascript variables as I need to.
C# Code:
StringBuilder colModel = new StringBuilder();
colModel.AppendFormat("var uiStrings = {{ captureStart: \"{7}\", captureOK: \"{0}\", captureRegister: \"{1}\", captureBad: \"{2}\", captureRegisterBad: \"{8}\", gridTitle: \"{3}\", gridIsCap: \"{4}\", gridNoCap: \"{5}\", gridDelete: \"{6}\", captureDiffUser: \"{9}\" }};",
this.GetLocalResourceObject("capOK").ToString(), this.GetLocalResourceObject("capRegisterOK").ToString(), this.GetLocalResourceObject("capBad").ToString(),
this.GetLocalResourceObject("gvCaption").ToString(), this.GetLocalResourceObject("gvIsCaptured").ToString(), this.GetLocalResourceObject("gvIsNotCaptured").ToString(),
this.GetLocalResourceObject("gvDelete").ToString(), this.GetLocalResourceObject("capStart").ToString(), this.GetLocalResourceObject("capRegisterBad").ToString(),
this.GetLocalResourceObject("capDiffUser").ToString());
ClientScript.RegisterStartupScript(this.GetType(), "initData", colModel.ToString(), true);
JavaScript:
$("#status").html(uiStrings.captureDiffUser);
Hope this helps!
You can use the GetGolabalRessourceObject Function.
$(function () {
$('#<%= ddlCustomer.ClientID %>').change(function ()
{
$('#<%=lblCustomer.ClientID%>').text('<%=GetGlobalResourceObject("lblCustomer")%>');
})
}
);

how to call jquery function call in asp.net c#?

I want to show division for 5 seconds while i do every postback in c#.I am using below function to do that but it doesn't work.
I used this code on page load in c#.
Page.ClientScript.RegisterStartupScript(Page.GetType(), "PostbackClick", "setTimeout(function() { $('#correct').fadeOut(1500); }, 5000)", true);
in aspx page
<script type='text/javascript' src='Scripts/scripts/jquery.min.js'></script>
<script type="text/javascript">
$(document).ready(function () {
$('#correct').hide();
});
</script>
<img alt="" id="correct" src="Que-img/correct.png" />
use
RegisterClientScriptBlock(Page.GetType(), "PostbackClick", "$(document).ready(function(){
setTimeout(function() { $('#correct').fadeIn(1500); }, 5000)});", true)
Because you have to wait for JQuery.ready before using jquery selectors. RegisterStartupScript actually happens before jquery ready.
in my answer your setTimer will executed on jquery ready
You already hiding the image in document.ready function
<script>
$(document).ready(function () {
//$('#correct').hide(); // remove this line or comment
// because fadeOut will work on visible elements
function hideImage() {
setTimeout(function() { $('#correct').fadeOut(1500); }, 5000);
};
});
</script>
In C#
Page.ClientScript.RegisterStartupScript(Page.GetType(),"PostbackClick", "script",
"hideImage();" true);
How to Call Jquery from C# will help you
I guess i got your issue ...Modify your code as below
$(document).ready(function () {
$('#correct').hide();
$('#btnId').click(function(){
$('#correct').show();
setTimeout(function() { $('#correct').fadeOut(1500); }, 5000);
});
});
and remove
Page.ClientScript.RegisterStartupScript(Page.GetType(), "PostbackClick", "setTimeout(function() { $('#correct').fadeOut(1500); }, 5000)", true);
Here is the demo

Can java script add the contents below to a table aswell

Can java script add the contents below to a asp table aswell at the same time (with html tags)
<script type="text/javascript">
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('textarea').val('');
$('#test1').append('<div id="test">' + x + '</div>');
return false;
});
});
</script>
<textarea style="border: 0" cols="77" rows="2">Write Something....</textarea>
<button>Post Message</button>
<div id="test1"></div>
</asp:Content>
something like:
<script type="text/javascript">
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('textarea').val('');
$('#test1').append('<div id="test">' + x + '</div>');
//$save append aswell to Table1
return false;
});
});
</script>
<script type="text/javascript">
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('textarea').val('');
var newdiv = $("<div></div>").html(x).attr('id','test');
$('#test1').append(newdiv);
$('#Table1').append(newdiv);
//$save append aswell to Table1
return false;
});
});
</script>
It seems like you are using jquery here.
Have you got your jquery framework loaded & tried your code to see if it works??
It is running fine on jsfiddle.net here
Updates
If your Table1 is on the same page.
All you need to do is to get hold of the DOM element.
if you have a table
<table id="Table1">
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</table>
You can add after your code
$('#test1').append('<div id="test">' + x + '</div>');
this code
$('#Table1 tr:last').after('<tr><td>'+ x +'<td></tr>');
Hope you find this helpful

Categories