Basically I want to set the default date on a jQuery calendar. I have a little script that runs fine when the page loads.
<script type="text/javascript">
$(function () {
var calendarPicker = $('input[name="ctl00$MainContent$ucDetails$LeftPanel$fieldDate$dateValue$calendarPicker"]');
if (calendarPicker.val() == "") {
calendarPicker.datepicker("option", "defaultDate", '<%# CalendarDefaultDate %>');
}
});
</script>
However, when the user changes the value on a combo box, the page posts back and runs some code which causes the value of CalendarDefaultDate to update. The problem is that even though the value of the property has changed, it doesn't get reflected on the page.
Any ideas how to fix this? Many thanks.
Update 1. Tried using the ClientScriptManager as advised. (with no joy)
StringBuilder builder = new StringBuilder();
builder.AppendLine("$(function(){var calendarPicker = $(\"input[name='ctl00$MainContent$ucDetails$LeftPanel$fieldDate$dateValue$calendarPicker']\")");
builder.AppendLine("if (calendarPicker.val() == '') {");
builder.AppendLine("calendarPicker.datepicker(\"option\", \"defaultDate\", '" + CalendarDefaultDate + "')");
builder.AppendLine("}});");
Page.ClientScript.RegisterStartupScript(GetType(), "CalenderDefaultDate", builder.ToString(), true);
You can use the ClientScriptManager to run your function on the reload:
ClientScriptManager.RegisterStartupScript(this.GetType(), "AKey", "MyFunction();", true);
http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx
Try to declare your function on aspx file this way.
<script type="text/javascript">
function assignCalendar () {
var calendarPicker = $('input[name="ctl00$MainContent$ucDetails$LeftPanel$fieldDate$dateValue$calendarPicker"]');
if (calendarPicker.val() == "") {
calendarPicker.datepicker("option", "defaultDate", '<%# CalendarDefaultDate %>');
}
};
</script>
Then in code behind call it like below:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "assignCalendar ", "<script type='text/javascript'>assignCalendar();</script>", false);
If you put it on PageLoad event i think it will work
Related
In the below code I have a dropdown in this I call js function from server side and I want to pass parameter to js function. In my case parameter is not passing. Please help me to solve this issue.
codebehind:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", "<script type=text/javascript> AddItem(" + EnumRows + ");</script>", true);
js:
function AddItem(EnumRows) {
// Create an Option object
// var opt = document.createElement("option");
alert('this');
// Add an Option object to Drop Down/List Box
document.getElementById("<%=cbField.ClientID%>").options.add(opt);
// Assign text and value to Option object
opt.text = Value;
}
Try this
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", "AddItem('" + EnumRows + "');", true);
Below will help you
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", "AddItem(" + EnumRows + ");", true);
Try to use escape_javascript method on your parameter.
<%= escape_javascript(your_parameter) %>
\\code
public ActionResult mapPartial(DataTable dt)
{
string strEvents = "[";
foreach (DataRow row in dt.Rows)
{
strEvents += "[" + row["Lat"].ToString() + ", " + row["Long"].ToString() + ", " + "\"" +
row["LastName"].ToString() + row["DateOfBirth"].ToString() + "\"" + "],";
}
strEvents = strEvents.Remove(strEvents.LastIndexOf(","));
strEvents += "]";
ViewBag.locpoints = strEvents;
return PartialView(dt);
}
//in the partial view page
<script type="text/javascript">
function mapInit(Viewbag.locpoints) {
var arr = $.parseJSON(Viewbag.locpoints);
//more code which assigns a map to div map below
}
</script>
<div id="map" class="map"></div>
How can i call the JS function immediately to render my map when the partial view is loaded. The partial method in the controller returns a string which is used as parameter in the JS function. Hope it makes sense.
Since you appear to be using JQuery why not:
<script type="text/javascript">
$(document).ready(function(){
var arr = $.parseJSON("#Viewbag.locpoints");
//more code which assigns a map to div map below
});
</script>
I also changed how you referenced your ViewBag value since the way you have it, it won't be be a string literal in JavaScript.
Also, as a side note consider using JSON serializer to convert your data into JSON. It is considered a bad practice to do it manually like you did above.
After you define it, you just call it. However, it looks like you are including the MVC Viewbag values in the JS function definition. You should be passing those values when you call the JS method:
<script type="text/javascript">
function mapInit(locPoints) {
var arr = $.parseJSON(locPoints);
//more code which assigns a map to div map below
}
mapInit(#(Viewbag.locpoints));
</script>
Note: This assumes you have jQuery loaded.
Consider using the onSuccess Ajax Option and wire up a javascript function where your jquery is written. For example you have following script written in your mainView that calls the partial View. Suppose you want do something when the anchor tag in your partial view is clicked
var fromPartial=function()
{
var v = $(this).closest("div");
var mId = v.attr('id');
if (mId == 'divDetail') {
event.preventDefault();
//what you want to achieve
}
}
Now in your partial view the anchor tag is created as shown below
#Ajax.ActionLink("Select", "AssignSpeaker", new {
conferenceId = ViewBag.ConferenceId, sessionId = session.Id },
new AjaxOptions() { HttpMethod="Get",
InsertionMode= InsertionMode.Replace, UpdateTargetId="yourTarget",
OnSuccess="fromPartial" })
We have implemented a much simpler solution.
_Layout.cshtml after #RenderSection("scripts", required: false) (and Jquery,etc.)
<script>
$(document).ready(function () { if (typeof partialScript !== "undefined") partialScript();});
</script>
Then, in your partial view:
<script type="text/javascript">
function partialScript() {
alert("hi");
}
</script>
This ensures the following:
jQuery is loaded
All main view scripts are loaded
DOM is ready
Try to call your controller via JQuery.
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'your_controller_url',
success: function (data) {
//Do your stuffs here
}
});
}
The only way you can do this is by calling your controller action using JQuery and have it return your partial view. Use Jquery to update whatever section of the page the partial view goes to and then call the javascript method you want to render the map
I've been trying to pass an ASP.NET variable to a javascript function without any luck so far.
What I have is:
A master page that is using several .js files under folder root/js
I'm trying to create a public variable that contains the username of a person and would like to send it to a function that is inside one of the js files mentioned above.
public string username;
...
username = User.Identity.Name.ToString();
my js is:
$(document).ready(function {
var username = "<%= username %>";
var element = document.getElementById("userid");
element.innerHTML = username; });
After executing this I get <%= username %> and not the actual value.
I tried a second approach:
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "customScript", "AssignValue('" + username + "');", true);
but I get function (e,t){return new x.fn.init(e,t,r)} as a result... I don't know what to do.
Any ideas will be highly appreciated!
Thank you!
// aspx
<asp:HiddenField runat="server" ID="hfUserName" />
// page_load:
hfUserName.Value = username;
// js
$(function() {
$("#userid").text($("input[id$='hfUserName']").val());
});
I am not so familiar with JavaScript, for that reason I need your help and advice! I have the following code in my asp button when is clicked. When the confirm box is displayed the user has two choices either to select OK or Cancel. The following code works in both of cases either OK or Cancel.
protected void cancel_Click(object sender, EventArgs e)
{
string url = "../../Default.aspx";
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "confirm('Data is not saved'); window.location.href = '" + url + "';", true);
}
However, what I am trying to do is to perform an if/then/else statement using JavaScript inside ClientScript function, and I don't know the correct syntax of that. e.g what I am trying to do
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "javascript:if(confirm('Data is not saved')== true) return {document.location.href = '../../Default.aspx'}; else {document.location.href = '../../Current.aspx'};", true);
Any advice would be appreciated!
Try the script before you add it server side, it easier to debug that way.
HereĀ“s two ways to write the if statement;
if (confirm('Data is not saved')) {
window.location.href = '../../Default.aspx';
} else {
window.location.href = '../../Current.aspx';
}
or even;
window.location.href = confirm('Data is not saved') ?
'../../Default.aspx' : '../../Current.aspx';
UPDATE
<asp:Button ID="cancel" runat="server" Text="Cancel" CausesValidation="false"
onClientClick="window.location.href = confirm('Data is not saved') ? '../../Default.aspx' : '../../Current.aspx';"
/>
Also note that you should rather use window.location than document.location.
On the click of a button, I call a JavaScript function. After getting the value, I need to perform some stuff from the value obtained in the code-behind. How should I call code-behind?
My aspx:
function openWindow(page) {
var getval = window.showModalDialog(page);
document.getElementById("<%= TxtInput.ClientID %>").value = getval;
//After this I need to perform stuff 'Upload(TxtInput.value)' into database from the code-behind
}
The button calling the function is set up in the following manner:
<button class="doActionButton" id="btnSelectImage" runat="server" onclick="openWindow('../rcwksheet/popups/uploader.htm')">Select Image</button>
My desired code behind (VB):
Public Sub btnSaveImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectImage.ServerClick
Dim inputFile As String = Me.TxtInput.Value
//do more stuff here
End Sub
So:
Is there a way to call code-behind from the JavaScript?
Can I somehow use the "onclick" property of a button to first go to a JavaScript and then to the code-behind?
Trigger a code-behind call "onchange" of the TxtInput.Value?
yes there is a way.
first, you can use javascript to submit the form after your return value is set in TxtInput.
function openWindow(page) {
var getval = window.showModalDialog(page);
document.getElementById("<%= TxtInput.ClientID %>").value = getval;
document.forms[0].submit();
}
then in your code behind, you can handle TxtInput's value in page load event.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (this.Input.Value != string.Empty)
{
this.Input.Value += "blah";
}
}
}
note: you may need Identifying control that caused postback
You can put the server side code into a web service, make a service reference in an asp:ScriptManager on your aspx page and then you can call/execute the web service from javascript by calling:
WebServiceClassName.MethodName(javascriptvariable, doSomethingOnSuccess)
Here is a link on doing that:
http://msdn.microsoft.com/en-us/magazine/cc163499.aspx
You can call the __doPostBack Event.
function openWindow(page) {
var getval = window.showModalDialog(page);
document.getElementById("<%= TxtInput.ClientID %>").value = getval;
__doPostBack('btnSelectImage', getval);
}
And on the server side in your code behind, you can get the value:
In the PageLoad method:
if (Request.Form["__EVENTTARGET"] == "btnSelectImage")
{
//get the argument passed
string parameter = Request["__EVENTARGUMENT"];
//fire event
btnSaveImage_Click(this, new EventArgs());
}