I have gleaned that it is possible to use conditional compiler directives and constants in Razor markup. I would like to know if there is a way to conditionally emit JavaScript text using these directives, as I seek to to below:
#section BodyPanelScript
{
<script type="text/javascript">
$(function () {
$(":password").val(null);
// Back up current names of package radio buttons, then make all their names the same for grouping.
$("#package-selector :radio[name$='.IsSelected']").each(function () {
$(this).attr("oldname", $(this).attr("name"));
});
$("#package-selector :radio[name$='.IsSelected']").attr("name", "Package.IsSelected");
// Hook the 'submit' click to restore original radio button names.
$("form#register :submit").click(function () {
$(":radio[name='Package.IsSelected']").each(function () {
$(this).attr("name", $(this).attr("oldname"));
});
});
});
</script>
#{
#if AUTO_FILL_REG
<text>
<script type="text/javascript">
$(function () {
$(":password").val("123456");
});
</script>
</text>
#endif
}
}
The constant AUTO_FILL_REG is defined in my Debug configuration, and tells the controller to populate the registration model with default values, so I don't have to always complete the form to test the process. Existing values in the model are ignored on the password field, so I resort to some JavaScript to populate this field. I would like to have this JavaScript conditionally emitted, but several attempts like the code above either result in the #if...#endif text being literally rendered, and the password populated, or nothing being rendered, regardless of build configuration.
This is not a particularly elegant solution, but it is simple. You can make a simple class like this
public static ConditionalValue {
public static bool AUTO_FILL_REG {
get {
#if DEBUG
return true;
#else
return false;
#endif
}
}
}
and then just reference this in your aspx. This is just one example of where you could place this property. You could do it as constants as well, but you get the idea.
Related
Hi can someone please tell me how I can load a PartialView into a div container I have prepared located in _Layout.cshtml (that is completely separate from the link itself). I want it loaded into the container on the click of the following action link:
<span>ContactUs</span>
I would like to do this without javascript because I need to create a model in my controller and pass it to the PartialView and I dont think its possible to pass a strongly typed model to a view using javascript.
If I wanted to I could use:
$('.colorboxLink').click(function () {
$('.colorbox_container').load(this.href);
});
but as I mentioned this does not give me the chance to create and pass a strongly typed model to the partial view...its important that I can create and pass a model to the view because Im getting a null reference exception when I try something like foreach(var item in Model.ItemList) in the partial view.
Heres what my controller looks like:
public virtual ActionResult RenderColorbox(string path)
{
return PartialView(path, null);
}
However, currently, clicking the action link simply renders the PartialView in a new blank page rather than inside the container I have set up.
Thank you all for your help.
EDIT: To load the colorbox I used the following as suggest:
$('.colorboxLink').click(function () {
$('.colorbox_container').load(this.href, function () {
var colorboxOptions = {
inline: true,
scrolling: false,
opacity: ".9",
fixed: true,
onLoad: function () {
$('#cboxContent').css({
"background": "white"
});
$('#cboxLoadedContent').css({
"margin-bottom": "28px",
"height": "558px"
});
}
}
$('#contactColorbox').colorbox(colorboxOptions);
});
But still loads without colorbox, but rather as a pop up modal.
but as I mentioned this does not give me the chance to create and pass
a strongly typed model to the partial view.
It gives you such chance. You are sending an AJAX request to the RenderColorbox action on the ContactPartial controller. Inside this action you can prepare and send whatever complex view model you want to the partial:
public ActionResult RenderColorbox(string path)
{
SomeComplexModel model = ...
return PartialView(path, model);
}
Also make sure that you cancel the default action of the link by returning false from the click handler:
$(function() {
$('.colorboxLink').click(function () {
$('.colorbox_container').load(this.href);
return false;
});
});
If you don't do this, when you click on the link, your AJAX call has barely any chance to execute before the browser redirects away to the target page.
I am using DOJO (1.7) together with ASP.NET. I have attached an onclick event to the submit button but am trying to validate on client side first. In plain javascript, if I used a 'return false' statement, that stopped the postback. However, returning false in the code does not stop the statement while using DOJO. I am a DOJO newbie and have no idea what to do. Thank you for your time.
require(["dojo/io/script", "dojo/on", "dojo/dom", "dojo/domReady!"],
function (script, on, dom) {
on(dom.byId("<%= btnSubmit.ClientID %>"), "click", function () {
dom.byId("<%= txtSellPercentage.ClientID %>").value = "farax";
return false;
}
)
});
I had to tweak the code a little. Apparently I was trying to call some event method without importing the particular script for events. So here goes
<script type="text/javascript">
require(["dojo/io/script", "dojo/on", "dojo/dom", "dojo/domReady!", "dojo/_base/event"],
function (script, on, dom, event) {
on(dom.byId("<%= btnSubmit.ClientID %>"), "click", function (e) {
dom.byId("<%= txtSellPercentage.ClientID %>").value = "farax";
event.stop(e);
}
)
});
</script>
I am trying to use jquery to select a checkbox when another checkbox is selected. This wuld have been easy if the ids of the checkboxes are constant but they can change so I have tried to use classes instead, unfortunately asp.net applies the class name on the span element wrapping the checkbox instead of applying on the checkbox directly, so i need to get the checkbox via the inner element of the parent span
<script type="text/javascript">
$(document).ready(function() {
$('#ctl00_ContentPlaceHolder1_Category_ctl00_ProductBusinessLine_chkEL_157').click(function() {
if (this.checked) {
var pl = $('#ctl00_ContentPlaceHolder1_Category_ctl00_ProductBusinessLine_chkPL_313')
pl.attr("checked", true);
}
})
});
</script>
My code, previously working with the checkbox ids, is above, pls help!
You can still match your check boxes even if the class attribute is applied to their parent <span> elements:
$(document).ready(function() {
$(".sourceCheckBoxClass input:checkbox").click(function() {
if (this.checked) { // or $(this).is(":checked")
$(".targetCheckBoxClass input:checkbox").attr("checked", true);
}
});
});
With ASP.NET you can control the ClientId of the form controls. You have the use the Clientid property as I remember.
More info at the MSDN.
<script type="text/javascript">
$(document).ready(function() {
$('#ctl00_ContentPlaceHolder1_Category_ctl00_ProductBusinessLine_chkEL_157').click(function() {
if (this.checked) {
var pl = $('#ctl00_ContentPlaceHolder1_Category_ctl00_ProductBusinessLine_chkPL_313 :checkbox')
pl.attr("checked", true);
}
})
});
</script>
Is that what you're looking for ? oh and looks like you're using ids, not classes in your selectors
if you write your javascript code on the page, then you can determine real id dynamically:
$('#<$=chkEL_157.ClientID%>').click(function() {
...
});
or find element by a part of id:
$(':checkbox[id$="_chkEL_157"]').click(function() {
...
});
but in this case you must assure that there is no other element that contains similar id. Otherwise you must specify context where you want to find element, like this:
$(':checkbox[id$="_chkEL_157"]', $("#checkbox-context-element")).click(function() {
...
});
What I would like to do is have the user add a new record to the database and popup a JQuery dialog confirming that the new record was saved. I thought this would be a simple exercise. I have a gridview bound to a LINQDataSource to allow the user to view and edit existing records and a textbox and a button to add new codes.
In the head of the document, I have the following:
$('#dialog').dialog({
autoOpen: false,
width: 400,
buttons: {
"Ok": function () {
$(this).dialog("close");
}
}
});
and futher down in the markup I have:
<div id="dialog" title="New Code Added">
<p>"<asp:Literal runat="server" ID="LiteralNewCode"></asp:Literal>" was successfully added.</p>
</div>
So when the user enters a new description and it passes all the validation, it's added to the database and the gridview is rebound to display the new record.
protected void ButtonSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
CCRCode.Add( <long list of paramters> );
GridCode.DataBind();
IsNewCode = true;
NewDescription = <new description saved to database>;
}
}
Now, here's where (I thought) I'd set a boolean property to indicate that a new description had been added as well as the text of the new description. See below:
protected bool IsNewCode
{
get { return ViewState["IsNewCode"] != null ? (bool)ViewState["IsNewCode"] : false; }
set { ViewState["IsNewCode"] = value; }
}
private string NewDescription
{
get { return ViewState["NewDescription"] != null ? ViewState["NewDescription"].ToString() : string.Empty; }
set { ViewState["NewDescription"] = value; }
}
Here's where I loose my way. My guess is I want to add functionality to include code similar to:
$('#dialog').dialog('open');
I've added a registerscriptblock method in the page_load event but that didn't work. Any ideas? Or am I just going about this entirely wrong?
Thanks.
Not really get what you want to do. But, i use jquery alot with .NET in my projects. here is how i do, probably could give you a hint.
foo.aspx.cs
public String ScriptToRun = "$('#dialog').dialog('open');";
change the value of ScriptToRun in your C# code
foo.aspx
$(document).ready(function() {<%=ScriptToRun %>});
Remember that whatever you done in backend is going to generate HTML, Css& javascript to browser.
Two ways: one, write the javascript in your server-side code. Or, define a JS method to show the dialog (say named showDialog), and call it via:
Page.ClientScript.RegisterStartupScript(... "showDialog();" ..);
RegisterStartupScript puts the method call at the end, ensure your script is above it to work. You can also wrap it with document.ready call too, to ensure JQuery is properly loaded.
I think that the only think that you have miss is the creation of the dialog when the Dom is ready.
$(document).ready(function() {$('#dialog').dialog('open');});
I posted code in a different question for a custom "MessageBox" class I wrote:
ASP.NET Jquery C# MessageBox.Show dialog uh...issue
the code by default uses the javascript alert() function, but you can define your callback so that it calls your custom javascript method to display the messages.
On load I'm both calling a JavaScript setTimeout() function that will hide a .NET Panel control, and hiding it in the code behind on first load. Clicking the save button will set the Panel to visible then reload the page at which point a setTimeout() function is called... so basically you click save, and see a panel with "Details Saved" for three seconds, at which point it disappears.
The problem is the external JavaScript file can't find _pDivAlert.ClientID (I've debugged and it returns null). It only works when the code is in a tag in the .aspx page. Any suggestions as to how I can either pass the client ID to the HideControl() function or find the ClientID from the external JS file?
Here's my code, any suggestions?
<script language="javascript" src="Forms.js" type="text/javascript"></script>
<body onload="ToggleAlert()">
<form id="form1" runat="server">
<script type="text/javascript">
//alert the user that the details were saved
function HideControl() {
var control = document.getElementById('<%=_pDivAlert.ClientID %>');
if(control != null)
control.style.display = 'none';
}
function ToggleAlert() {
setTimeout("HideControl()", 3000);
}
</script>
I've also tried sending the ClientID within the ToggleAlert() call, but that didn't work:
<body onload="ToggleAlert('<%=_pDivAlert.ClientID %>')">
External JS:
function HideControl(_c) {
var control = _c;
if (control != null)
control.style.display = 'none';
}
function ToggleAlert(_c) {
setTimeout("HideControl(_c)", 3000);
}
can you show your markup with the panel and the codebehind where you hide it?
there's a difference between setting the Visible property to false and setting the style display attribute to none- the first will not render the element at all, meaning there isn't anything rendered with the id you're looking for.
edit: it's probably because of the way you're calling HideControl in the timeout- this should be a function instead of a string.
try doing
function ToggleAlert(_c) {
setTimeout(
function () {
HideControl(_c);
}, 3000);
}
just for clarity, when you pass a string to setTimeout, it's evaluated and then run. the code chunk that eval produces will run in a different scope than your ToggleAlert method, and so _c won't be available at that time.
edit: you also need to actually get a reference to the control. you're passing the id string to ToggleAlert, which relays it to HideControl, which is expecting an object not a string.
function HideControl(_c) { // _c is the id of the element
var control = document.getElementById(_c);
if (control != null)
control.style.display = 'none';
}