MVC View User Control with JavaScript. How implement popup? - c#

I have a small project which I have a page with a drop-down menu. When the drop-down is selected a user control should popup.
This is an image of what I'm hoping to acomplish:
I have a .ascx file which needs to be loaded. Where would the entry point be added to have this control pop-up?
Here is the implementation. I have started with. This project is not using the code behind and is instead using javascript to implement controls.
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<AdministratorConsole.Models.TaskActionController.TaskActionViewModel>" %>
<script language="javascript" type="text/javascript">
<!-- Some Funtions -->
</script>
<div class="main_popup_container">
<div class="task-action-header">Action Type: Hyperlink PDFs</div>
<div class="task-configuration-header">Configuration<span id="HyperlinkCopyTestResults" class="one-line-test-results"></span></div>
I have started a method to try to get this .ascx to pop up from the root folder without any luck. What do I need to get this MVC view user control to popup
and execute?
class PageLoad : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Load control from file
Control load = (Control)Page.LoadControl(#"~/PDFHyperlink.ascx");
}
}
I also have a Interface which has and Execute GetName and TestConfiguration to run some test on user inpute and execute my code to hyperlink PDFs.
public bool Execute(TaskActionConfig action, TaskActionAPI.Task t, out string message)
{
message = GetName();
string configMessage = "Test Message";
bool result = TestConfiguration(action, out configMessage);
// Run hyperlinking tool.
HyperlinkingTool(t);
return true;
}
// **************************GetName**************************
public string GetName()
{
string HyperlinkPDFs = "Hyperlink PDFs";
return HyperlinkPDFs;
}
// **************************TestConfiguration**************************
public bool TestConfiguration(TaskActionConfig action, out string message)
{
Dictionary<string, string> parameter = action.Parameters;
bool result = true;
message = "Config Message";
return result;
}

The method GetName() needs to return the same name as the .ascx file. This will register the .ascx file and load it.

Related

ASP.NET Generic UserControl with Html Content Placeholder

This question might have already been asked, but I could not find any references to it so I apologize if it seems like a duplicate question.
What I'm trying to do is create a generic DialogBox as an ASP.NET UserControl; which would contain all the script required to create the dialog using jQuery. The dialog has a fixed set of buttons, but I'd like to be able to let the user define the content when they create the dialog. Suppose this is the markup for the user control:
<head>
<script type="text/javascript">
// jQuery script to create the dialog
</script>
</head>
<body>
<div runat="server" id="divContainer">
<!--Html Content Placeholder. What goes here?-->
</div>
</body>
And the code-behind:
[ParseChildren(true, "Contents")]
public partial class UCDialogBox : ExtendedUserControl
{
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
}
public List<Control> Contents { get; set; }
public DialogType Type { get; set; }
public string Title { get; set; }
}
And on the actual page after registering the control, I would like to be able to do something like this:
<uc:DialogBox runat="server">
<div>
<label>Hello World</label>
</div>
</uc:DialogBox>
The problem with this is, List<Control> only allows for ASP.NET controls. Normal HTML controls (such as what I have above) won't work.
Question 1: What type should I use to allow any HTML control to be nested inside the user control? I tried System.Web.UI.HtmlControls.HtmlControl but that didn't work either (ASP.NET says The element 'div' cannot be nested within the element 'dialogbox').
Question 2 What would I put as an HTML content placeholder on the user control which can be bound to the Contents property on the code behind? Something like
<SomePlaceholderControl DataSource="<%# Contents %>" />
Any help is appreciated.
Oddly enough, putting HTML controls inside the body of the user control doesn't cause a run-time error. In fact, the controls come across just fine. I guess it's just the designer that whines about it.
As for the placeholder, I didn't have to use any specific control; I simply used an HtmlTextWriter to render the controls into a well-formatted HTML string inside a method that gets called in the markup:
<div runat="server" id="divContainer">
<%# RenderContents() %>
</div>
And the code-behind method:
public string RenderContents()
{
StringWriter writer = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
foreach (var control in Contents)
{
control.RenderControl(htmlWriter);
}
return writer.ToString();
}
It works just fine.
I am not sure whether this is the correct approach, I have added a ITemplate inside the Dialog control and placed a HtmlGenericControl container which is Div control with runat = "server".
Now you can add the html controls and text inside this container.
<cc1:UCDialogBox ID="dialog" runat="server">
<HtmlPlaceHolder>
<div runat="server">
<h1>Title</h1>
<h2>Description</h2>
<div>Modal Content</div>
</div>
</HtmlPlaceHolder>
</cc1:UCDialogBox>
In custom server control you can get the container div content as innerHtml or innerText
public class UCDialogBox : WebControl, INamingContainer
{
private ITemplate htmlPlaceHolder = null;
[
Browsable(false),
DefaultValue(null),
Description("Add your html contorls"),
PersistenceMode(PersistenceMode.InnerProperty)
]
public virtual ITemplate HtmlPlaceHolder
{
get
{
return htmlPlaceHolder;
}
set
{
htmlPlaceHolder = value;
}
}
protected override void Render(HtmlTextWriter output)
{
HtmlGenericControl placeholder = new HtmlGenericControl();
htmlPlaceHolder.InstantiateIn(placeholder);
var html = placeholder.Controls[1] as System.Web.UI.HtmlControls.HtmlGenericControl;
var result = html.InnerHtml.Replace("\r", "").Replace("\n", "").Trim();
output.Write(result);
}
}

Need Sharepoint like modal pop-up window

I need to show Sharepoint 2010 like pop-up window when clicked on a link in grid view. Once the modal pop-up displayed and user selected the Save button data base should be updated with given values in pop-up. How can I get this. Any Idea.
As of now I am using below code to get it but no idea how to pass the values to Database once clicked on the button in pop-up
Note: As of now I am not adding the gridview code here as I wanted to achieve it first with sample html then wanted to do with grid view.
Java Script
function openDialog() {
var options = {
html: divModalDialogContent, // ID of the HTML tag
// or HTML content to be displayed in modal dialog
width: 600,
height: 300,
title: "My First Modal Dialog",
dialogReturnValueCallback: dialogCallbackMethod, // custom callback function
allowMaximize: true,
showClose: true
};
SP.UI.ModalDialog.showModalDialog(options);
}
//Results displayed if 'OK' or 'Cancel' button is clicked if the html content has 'OK' and 'Cancel' buttons
function onDialogClose(dialogResult, returnValue) {
if (dialogResult == SP.UI.DialogResult.OK) {
alert('Ok!');
}
if (dialogResult == SP.UI.DialogResult.cancel) {
alert('Cancel');
}
}
// Custom callback function after the dialog is closed
function dialogCallbackMethod() {
alert('Callback method of modal dialog!');
}
HTML
<div id="divModalDialogContent">
Hello World!
<input type="button" value="OK"onclick="SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, 'Ok clicked'); return false;"
class="ms-ButtonHeightWidth" />
<input type="button" value="Cancel"onclick="SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 'Cancel clicked'); return false;"
class="ms-ButtonHeightWidth" />
<asp:Button runat="server" ID="btnClicked" Text="Clicked"
onclick="btnClicked_Click" />
<input type="button" value="Open" onclick="openDialog()" />
How can I call db upon clicking 'clicked' button in pop-up. Also I need to send parameters to pop-up
Thanks in advance
If you need ok, cancel or submit button event on popup screens which interacts with Sharepoint list/library or sql database then you need to implement event in your popup. Check below steps:-
your popup page should inherit "Microsoft.SharePoint.WebControls.LayoutsPageBase"
which should have this function:-
protected void EndOperation(int result, string returnValue)
{
string closeModal = String.Format(CultureInfo.InvariantCulture,
"<script type=\"text/javascript\">window.frameElement.commonModalDialogClose
({0}, '{1}');</script>", new object[] { result, returnValue });
this.Page.ClientScript.RegisterStartupScript(base.GetType(),
"CreatePopup", closeModal, false);
}
Implement an event which can be listen on popup action like ok button
public delegate void AddEventHandlerToSPDialogEvent(object sender, PDialogEventHandler e);
public class SPDialogEventHandler : EventArgs
{
public int dialogResult { get; set; } // 0 or 1
public string ReturnValues { get; set; } // can be url or any success/error message
public SPDialogEventHandler(int result, string list)
{
ReturnValues = list;
dialogResult = result;
}
}
Call this event from your button action in popup. for ex:
public event AddEventHandlerToSPDialogEvent ResultOk;
protected void CancelBtn_Click(object sender, EventArgs e)
{
try
{
int dialogResult = 0;
if (this.ResultOk != null)
{// Here dialogResult is 0. that means we have clicked on cancel button
ResultOk(this, new SPDialogEventHandler(dialogResult,"Action Cancelled"));
}
}
catch (Exception ex) { }
}
You can use the Ajax control toolkit, then you should look for the modal popup extender.
Like that you can add .net controls into the overlay/modal overlay and get the values in code behind
for more info see here
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ModalPopup/ModalPopup.aspx
SP Popup
Open a modal/pop up form in Sharepoint 2010 with asp.net controls in it

How to remove the error like "Expected ;" in Tridion popup page?

I am customizing the ribbon toolbar and adding a button to it. Whenever I click on that button, it will open a aspx page allows authors to select some data, which gets appended to the existing RTF field content.
But when popup is opened it is having the below error in the browser (Internet Explorer).
I am inheriting Tridion page in the code behind file. When I try to use Response.Write() functions it is giving error like "Expected ;". Please tell me the reason why it is giving the error like that? Early responce is appreciated. Thanks in advance.
PFB the related code:
Aspx page code behind file contents:
namespace ButtonReference.Popups
{
[ControlResourcesDependency(new Type[] { typeof(Popup), typeof(Tridion.Web.UI.Controls.Button), typeof(Stack), typeof(Dropdown), typeof(List) })]
[ControlResources("RTFExtensions.ButtonReferenece")]
public partial class PopupReference : TridionPage
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
TridionManager tm = new TridionManager();
tm.Editor = "PowerTools";
System.Web.UI.HtmlControls.HtmlGenericControl dep = new System.Web.UI.HtmlControls.HtmlGenericControl("dependency");
dep.InnerText = "Tridion.Web.UI.Editors.CME";
tm.dependencies.Add(dep);
System.Web.UI.HtmlControls.HtmlGenericControl dep2 = new System.Web.UI.HtmlControls.HtmlGenericControl("dependency");
dep2.InnerText = "Tridion.Web.UI.Editors.CME.commands";
tm.dependencies.Add(dep2);
//Add them to the Head section
this.Header.Controls.Add(tm); //At(0, tm);
}
protected void Page_Load(object sender, EventArgs e)
{
mySession = new Tridion.ContentManager.Session(#"");
if (!Page.IsPostBack)
{
try
{
if (true)
{}
else
{
//Response.Write("Invalid schema chosen");
return;
}
}
}
}
}
Small remark: since your page will be used as a simple popup, you don't need to load Domain Model related JavaScript stuff. Not loading it will reduce the load time for your page. To do that you need to set IsStandAloneView Tridion Manager property to false:
tm.IsStandAloneView = false;

"System.NullReferenceException-- Object reference not set to an instance of an object." Webmethod, User control

I have a ModalPopupExtender(mpe) which will show when a asp:button is clicked. The button calls a javascript function which then calls a webmethod. The webmethod is in the code behind of the page.
The webmethod passes a string variable to another method in the code behind. which determines what the mpe does. The idea behind this logic is that when you click the button I want to enable certain parts of the mpe and disable other parts. This is because the mpe has several functionalities.
Aspx Button and UserControl
<uc2:IMG ID="IMG1" runat="server" />
<asp:Button ID="btnAddNewImg" runat="server" Text="Add New Image" onclientclick="ShowImgPopupScreen()" />
Javascript function
<script type="text/javascript">
function ShowImgPopupScreen() {
// call server side method
PageMethods.AddNewImg();
}
</script>
ASPX.CS code
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static void AddNewImg()
{
string option = "add";
image_loader_cms cms = new image_loader_cms();
cms.SetButtons(option);
}
protected void SetButtons(string add)
{
if (add == "add")
{
IMG1.Add = true;
}
else
{
IMG1.Edit = true;
}
}
ASCX.CS
public bool Add
{
get
{
return btnAdd.Enabled;
}
set
{
btnAdd.Enabled = value;
}
}
public bool Edit
{
get
{
return btnUpdate.Enabled;
}
set
{
btnUpdate.Enabled = value;
}
}
The code steps into IMG1.Add = true; when using breakpoints but after that line of code I get this error message.
Microsoft JScript runtime error: Sys.Net.WebServiceFailedException: The server method 'AddNewImg' failed with the following error:
System.NullReferenceException-- Object reference not set to an instance of an object.
This problem has me scratching my head.
You are creating a new usercontrol, however it wont create its child controls or be in anyway usable until it is added to the control tree, hence your image and buttons are never created.
Since you are in static page method, i dont think this is going to work.
What are you actually trying to do with the user control from the page moethod ?

ASP.net get content page to change master page control

Master page:
<form runat="server">
<Scirra:MainMenu runat="server" ID="MainMenu" TopTabSelected="home" SubTabSelected="link2" />
<asp:ContentPlaceHolder id="MainContent" runat="server">
snip
Content page:
Master.MainMenu.TopTabSelected = "forum";
I know I'm probably doing this wrong, but is this possible? I want to change a parameter of that control. It says 'inaccessible due to protection level'.
You should provide a public property f.e MenuTabSelected in your MasterPage that Gets/Sets this property of your Menu.
public string MenuTabSelected {
get { return MainMenu.TopTabSelected; }
set { MainMenu.TopTabSelected = value; }
}
Then you can access it in this way:
((YourMasterPage)Master).MenuTabSelected = "forum";
where YourMasterPage is the type of your MasterPage.
The compiler error is thrown because you want to access a private or protected control from outside of your MasterPage-Class. This would only be allowed if it would be public, what is not recommended. You have more control if you do it the way i suggested :)
find menu items in content page and change its value
protected void Page_Load(object sender, EventArgs e)
{
Menu mainMenu = (Menu)Page.Master.FindControl("NavigationMenu");
MenuItem menuMaterials = mainMenu.FindItem("Materials");
if (menuMaterials.Value == "Materials")
{
menuMaterials.Value = "NO materials";
menuMaterials.Text = "No materials";
}
}

Categories

Resources