Sharepoint Custom text Web part Property - c#

When a user enters custom text in a web part property. It will display on a form.
this is the code for the web part property it is on the the testTextWebPart.ascx.cs
public partial class testTextWebPart: WebPart
{
private string _customtxt;
[WebBrowsable(true),
Category("Miscellaneous"),
Personalizable(PersonalizationScope.Shared),
WebDisplayName("Enter some text")]
public string CustomTextProp
{
get
{
return _customtxt;
}
set
{
_customtxt = value;
}
}
I need to display the text onto a form.This page is testTextWebPart.ascx
<script type="text/javascript">
function NAME() {
var ctx = new SP.ClientContext.get_current();
var webURL = ctx.get_url;
var newFormURL = window.location.protocol + '//' + window.location.host + webURL + '/Lists/Testpage/NewForm.aspx';
var options = SP.UI.$create_DialogOptions();
options.title = 'PAGE TITLE';
options.url = newFormURL;
SP.UI.ModalDialog.showModalDialog(options);
}
I need to display it here. This is in my Control templates folder this page is testText.ascx
<div id="divForm" runat="server" style="width:400px; margin-left:auto; margin-right:auto; margin-top:10px;">
<div style="margin-bottom:10px;"> DISPLAY HERE </div>
I need to get the text the user entere via the webpart properties and then display it on the form when the user clicks the newform.

You can just add this method to your code:
protected override void CreateChildControls()
{
base.CreateChildControls();
LiteralControl message = new LiteralControl();
message.Text = CustomTextProp;
Controls.Add(message);
}

Related

MVC View User Control with JavaScript. How implement popup?

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.

Separate button triggers "Please fill out this field"

I am building a web app with C# and asp.net. In the webpage, there is a header with a search bar and a body with a form. When I enter something in the search bar, one of the form fields shows the pop-up, "Please fill out this field".
This field is required, but for the form which has a separate submit button. So what I'm saying is my search button and form are connected but they shouldn't be.
Edit:
Code behind for the search button:
protected void btnOpenModalSearch(object sender, EventArgs e) {
//get information from database to populate the modal box with
PopulateModalBoxGridView();
ScriptManager.RegisterStartupScript(this, this.GetType(), "Properties",
\ "openModal();", true);
}
protected void PopulateModalBoxGridView() {
if (dtSearch == null) return;
//sort the search results in data table
DataView dvSearch = dtSearch.DefaultView;
dvSearch.Sort = SortOrder;
gridSearchResults.DataSource = dvSearch;
gridSearchResults.DataBind();
}
Code behind for the separate form:
protected async void btnCreateNewAsset_Clicked(object objSender, EventArgs evntArgs) {
//create a new asset
//first check for duplicates
if (IsDuplicateAsset()) { return; }
Asset newAsset = new Asset {
//creating asset
};
//post the asset to Team Dynamix
var addAssetUri = new Uri(locationOrigin + webApiBasePath + addAssetPath);
responseMsg = await httpClient.PostAsJsonAsync(addAssetUri, newAsset);
httpResponse = responseMsg.Content.ReadAsStringAsync().Result;
if (!responseMsg.IsSuccessStatusCode) {
Notification.Show(this, "Error. Response content=" + httpResponse, Status.Error);
}
else {
Notification.Show(this, "Successfully Created Asset.", Status.Success);
assetDictionary.Add(serialNumber.Text, serialNumber.Text);
ClearTextFields(frmIndex);
}
}
I found the answer here: HTML 5 required validator triggers on all buttons on the form
To save you the trip, I needed to add formnovalidate="formnovalidate" to my button
<asp:ImageButton ID="BtnSearch" formnovalidate="formnovalidate" data-target="#myModal" ClientIDMode="Static" runat="server" ImageUrl="~/images/search.svg" Text="Search" OnClick="btnOpenModalSearch"></asp:ImageButton>

checkbox status lost after update panel works

I have an update panel, which fires every third seconds. I have this code into my asp.net page
<div ID="campaignDiv" runat="server" >
<ul>
</ul>
</div>
and I add its content dynamically like this:
private string CreateLiCheckbox(string checkBoxText)
{
return string.Format("<li><span class=\"textDropdown\">{0}</span><input id=\"{1}\" value=\"{0}\" type=\"checkbox\"><label for=\"{1}\"></label></li>", checkBoxText, checkBoxText + "dropdownID");
}
if (!IsPostBack) {
List<string> comps = getCompainNames();
string html = "<ul>";
for (int i = 0; i < comps.Count(); i++) {
html = html + CreateLiCheckbox(comps[i]);
}
html = html + "</ul>";
campaignDiv.InnerHtml = html;
}
My problem
when the page loads, the checkboxes are like this:
Then, I change the values to these:
but when the update pannel works, the page returns to its default statues, where nothing of the checkboxes are selected
could you help please?

Trying to programatically add div with spans within to a div on an asp.net page. Getting errors/null references

I have a dynamic number of data elements that need to be added to my asp.net page. I am currently trying to do this by looping through a result data set like this:
protected void Page_Load(object sender, EventArgs e)
{
UserDB db = new UserDB();
string employeeIDOrName = Request.QueryString["employeeID"];
DataSet ds = db.GetUserSearch(employeeIDOrName);
DataTable table = ds.Tables[0];
foreach (DataRow row in table.Rows)
{
string employeeID = row[0].ToString();
string emailAddress = row[1].ToString();
string phone = row[2].ToString();
string details = emailAddress + " | " + phone;
UserControl uc = new Controls_EmployeeSearchResults(employeeID, details);
placeholder1.Controls.Add(uc);
}
}
Then in the employeeSearchResults code, I have:
<div class="returnDataBoxSup" onclick="insertAddedSup('1091912','Shawna Burns');">
<div id="searchResults" runat="server">
</div>
</div>
for the ascx page and
public Controls_EmployeeSearchResults(string name, string details)
{
/*<div class="returnDataBoxSup" style="overflow:hidden;" onclick="insertAddedSup('1091912','Shawna Burns');">
<span ID="spanName" runat="server" style="text-transform:capitalize; white-space:nowrap"></span><br />
<span ID="spanDetails" runat="server" style="font-size:0.7em; white-space:nowrap"></span>
</div>*/
//Div
HtmlGenericControl div1 = new HtmlGenericControl("div");
div1.ID = "returnDataBoxSup";
div1.Attributes["style"] = "overflow:hidden;";
div1.Attributes["onClick"] = "insertAddedSup('1091912','Shawna Burns');";
div1.Attributes["class"] = "returnDataBoxSup";
//Span Name
HtmlGenericControl span1 = new HtmlGenericControl("span");
span1.ID = "span_" + name;
span1.Attributes["style"] = "text-transform:capitalize; white-space:nowrap";
span1.InnerHtml = name;
//Span Details
HtmlGenericControl span2 = new HtmlGenericControl("span");
span2.ID = "spanD_" + name;
span2.Attributes["style"] = "font-size:0.7em; white-space:nowrap";
span2.InnerHtml = details;
div1.InnerHtml = span1.ToString();
div1.InnerHtml += span2.ToString(); ;
//div1.Controls.Add(span1);
//div1.Controls.Add(span2);
//searchResults = new HtmlGenericControl("div");
searchResults.InnerHtml = div1.ToString();
}
in the code behind. I first tried to add the span controls to the div, but I was receiving an exception. When I tried to add the controls to the inner html, it said that it could not convert the control type to string. Is there any way that I can do what I am trying to do?
I receive employee data in a data set, then I want to loop through those and create a stylized div for each employee record and display it on my page. Any thoughts?
Using the user control isn't a bad idea, using a ListView could be a lot better/easier though.
But lets say you stick with a div and a user control for now. Firstly, you don't create usercontrols the same way you create other controls because you are part way through the page life cycle and they need to be caught up. Instead use LoadControl (see: https://stackoverflow.com/a/4786121/328968).
Second, don't pass the values into the constructor. Create a function in your usercontrol called LoadData and pass the values to that. After creating your usercontrol using LoadControl you call LoadData and pass in the values. LoadData takes care of loading the data into the various controls which, unlike your example, should probably already exist in your usercontrol.
Try the InnerText to see if it works.

How to create custom control of existing user control

I have created one user control for multiple file upload ,
i need to create its custom control so that I can have a dll of that control.
What are the ways that I can do this?
usercontrol.ascx
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.MultiFile.pack.js" type="text/javascript"></script>
<div><%-- accept attribute can be used like accept="png|jpg"--%>
Multiple File Upload<br />
<asp:FileUpload ID="FileUpload10" runat="server" class="multi" accept="" />
<asp:Button ID="Button3" runat="server" Text="Submit" OnClick="jQueryUploadFiles" />
<br />
<asp:Label ID="lblMessage" runat="server" EnableViewState="false" ForeColor="Green" />
<br />
<asp:Label ID="lblError" runat="server" EnableViewState="false" ForeColor="Red" />
</div>
usercontrol.ascx.cs
private void FileUploadUsingJQuerySelectionMethod()
{
// check if file has been selected
HttpFileCollection files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (file.ContentLength > 0)
{
string path = ConfigurationManager.AppSettings["FilePath"];
string fileName = Path.GetFileName(file.FileName);
// now save the file to the disk
file.SaveAs(path + fileName);
lblMessage.Text += "File : <b>" + fileName + "</b> uploaded successfully !<br />";
}
}
}
I tried like following:
public class MultipleFileUpload : WebControl
{
#region declare controls here
Label lblMessage;
Label lblError;
FileUpload FileUpload10;
Button btnUpload;
#endregion
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string FilePath
{// prop to get filepath
get
{
String s = (String)ViewState["FilePath"];
return ((s == null) ? "[" + this.ID + "]" : s);
}
set
{
ViewState["FilePath"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
output.Write(FilePath);
}
// create the layout (html) of your control here
// all the HTML code including <div>
// Add all controls to the <div>, below code is very crude.<br/>
// Also you need to register the script tags and add the script to it<br/>
protected override void CreateChildControls()
{
base.CreateChildControls();
Table table = new Table();
this.Controls.Add(table);
lblMessage = new Label();
lblMessage.ID = "lblMessage";
lblError = new Label();
lblError.ID = "lblError";
FileUpload10 = new FileUpload();
FileUpload10.ID = "FileUpload10";
btnUpload = new Button();
btnUpload.ID = "btnUpload";
btnUpload.Text = "Submit <br/> ";
// table.Controls.Add(lblMessage);
}
// invoke this method were ever required
private void FileUploadUsingJQuerySelectionMethod()
{
// check if file has been selected
HttpFileCollection files = HttpContext.Current.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (file.ContentLength > 0)
{
string path = FilePath;
string fileName = Path.GetFileName(file.FileName);
// now save the file to the disk
file.SaveAs(path + fileName);
lblMessage.Text += "File : <b>" + fileName + "</b> uploaded successfully !<br />";
}
}
}
You can put your control in a dll following the steps detailed here: Turning an .ascx User Control into a Redistributable Custom Control.
I think that it would be worth converting your user control to a proper server control, however, it's not that hard and you would end up with easier to maintain code (as you will see, the process described there is rather awkward).
You could add the js files by embedding them in the dll i.e.
Including them as normal in the custom control project
Right clicking and selecting 'embedded resources'
Accessing through the resource manager as they are now part of the default resource file i.e.
Stream ms = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("resourcename including namespace");
Then read the stream to get the script as a string
Register the script string with ScriptManager in the usual way
To build a web control you need to inherit from UserControl or another control, in your case FileUpload, then override the init event to add other controls (e.g. button) to the tree. Override any other events as needed.
Old article but pretty clear e.g. of principal:
http://www.codeproject.com/KB/validation/textboxwithvalidator.aspx

Categories

Resources