I'm using Umbraco 4.7.1 and have created a custom DocumentType called "Partner". I want to use that custom DocumentType in a masterpage. I'll show the code.
public class Partner : IdentifyingMarkRemoved.DocumentTypes.Page {
[DocumentTypeProperty(UmbracoPropertyType.Textstring, Mandatory = true, Tab = "Content")]
public string PartnerName { get; set; }
[DocumentTypeProperty(UmbracoPropertyType.Textstring, Mandatory = true, Tab = "Content")]
public string PartnerLevel { get; set; }
[DocumentTypeProperty(UmbracoPropertyType.Upload, Mandatory = true, Tab = "Content")]
public string PartnerLogo { get; set; }
[DocumentTypeProperty(UmbracoPropertyType.RichtextEditor, Mandatory = true, Tab = "Content")]
public string PartnerDescription { get; set; }
}
Thats the custom DocumentType.
The Masterpage looks like this:
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div id="partnerName"><%= this.CurrentContent.PartnerName %></div>
<div id="partnerLevel"><%= this.CurrentContent.PartnerLevel %></div>
<div id="partnerLogo"><%= this.CurrentContent.PartnerLogo %></div>
<div id="partnerDescription"><%= this.CurrentContent.PartnerDescription %></div>
</asp:Content>
Essentially what happens is a user will create a new page of type "Partner" and the application will demand those four pieces of information from them.
The user will upload an image and when the resulting page is created, the image is shown on the page.
Problem is, what I am getting when I test is this:
partnersname
partnerslevel
/media/541/plogo.jpg
Random text again
I have tried to represent the PartnerLogo as a type "object" so I could cast it to a type "Image" but that gives me an error.
I've tried doing that in the code behind, but again, I get an error.
I have attempted various combinations of quotes and nested asp commands, but nothing seems to be working.
I do have the sense that I'm on the edge of getting this right, but I'm too much of an ASP noob to know where I'm going wrong.
Looking forward to some help!
The image is stored as a string, referencing the URL the image is to be found at. So you will need to add your own tag in the HTML.
Something like this should work:
<img src='<%= this.CurrentContent.PartnerLogo %>' />
Related
I have this Web Control call uc_Register.asxc
Inside this web control got a Text Box i.e txtName
I add this Web Control into my web page call register.aspx
<%# Register Src="~/controls/uc_Register.ascx" TagPrefix="ecommmbs" TagName="uc_Register" %>
<hr />
<ecommmbs:uc_SummaryCart runat="server" ID="uc_SummaryCart" />
<hr />
i want to get the value from txtName.txt from uc_Register.asxc at register.aspx.
how to make this happen?
Try this in Register.aspx
TextBox txtbox = (TextBox)uc_Register.FindControl("txtName");
but keep in mind Page_Load() of aspx page is called first than Page_Load()of .ascx is called.
Here is an example:
Declare On User Control (PrevTransList2.ascx.cs)
public string TransHxPage
{
get
{
return name;
}
set
{
name = value;
}
}
On Class file
public interface IUserControlTransHx
{
string TransHxPage { get; set; }
}
txtSomthing.Text = TransHxPage;
Now On Web page SET its values
PrevTransList2.TransHxPage = "POSP";
I am running into an issue where I have multiple forms with a number of controls on them (20-40). The problem is that when I handle the postback, I need to put their values into variables and if they are not asp.net server controls (i.e select, input, etc...) I sometimes need to make sure they even exist. So, if I have a plain html checkbox, which is unchecked, it will not be posted to the server and you need to check for its existence, before being able to get its value. After that I need to pass them into a method to save to the database. The method handles all my crud and business validation. Setting this up is tedious at best and very time consuming. What are people doing to handle this? I am using ASP.Net 4.0 Web forms and VB.Net. One thought was to pass the http context into the method and let the code in the method look for the values. Still, doesn't seem that good of a solution. Any advice would really be appreciated, since I know I am not the only one who has run into this problem. Thanks in advance.
Wade
For large forms, you can:
create javascript object on client, convert it to JSON string, put JSON string to ASP .NET control Hidden or invisible textarea;
submit form and deserialize JSON to object on server.
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.validation.net.webforms.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:HiddenField runat="server" ID="Hidden1" />
<input type="checkbox" id="CheckBox1" checked />
<input type="checkbox" id="CheckBox2" />
<input type="text" id="text1" name="text1" value=""/>
<asp:Button runat="server" Text="Button" ID="Button1" OnClientClick="createJSON()" OnClick="Button1_Click" />
<script type="text/javascript">
function createJSON() {
$('#Hidden1').val(JSON.stringify({
field1: $('#CheckBox1').is(':checked'),
field2: $('#CheckBox2').is(':checked'),
field3: $('#text1').val()
}));
}
$(document).ready(function () {
$("#form1").validate({
onsubmit: false,
rules: {
text1: {
required: true,
digits: true
}
}
});
$("#Button1").click(function (evt) {
var isValid = $("#form1").valid();
if (!isValid) evt.preventDefault();
});
});
</script>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Web.Script.Serialization;
public class myClass
{
public bool field1;
public bool field2;
public string field3;
}
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
var result = (myClass)(new JavaScriptSerializer()).Deserialize(Hidden1.Value, typeof(myClass));
}
}
Install validation:
PM> Install-Package JQuery.Validation
PM> Install-Package JQuery.Validation.WebForms
From the moment that some controls they not post back any value, like the check box if is not checked you have two options.
Know all your controls before and after the post back / or
Create with javascript all the names of the controls and post them back in a hidden field.
Now, on the post back you have all the posted values on the HttpContext.Current.Request.Form where you can read them all.
On the client side you can use simple javascript or jQuery to create the list of all input controls and send them on a hidden input. Here is an example:
var inputs, index, cNames = "";
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
cNames += "&" + inputs[index].name;
}
document.getElementById("AllControls").value = cNames;
or the same with jQuery
var cAllNames = "";
$('input').each(function() {
cAllNames += "&" + $(this).attr("name");
});
jQuery('#AllControls').val(cAllNames);
and on your page you have a hidden control like
<input type="hidden" name="AllControls" id="AllControls" />
and on the post you have all the names of your controls in a line like:
AllControls=&__VIEWSTATE&__EVENTVALIDATION&cbBoxTest&AllControls&Button1
There you can split that string, each name is seperated with the &, and there you can see what is used, what is not. You can either pass additional informations about that controls - the same way I send the name of each.
For each web form create a model class that has public properties with all the fields that may be on the form. Create name, validation and default value attributes and apply them to the properties. During the postback, find out what the model class is needed, create an instance, iterate its public properties and apply: if post has the field with property name - validate the value and apply to the field, if not - apply the default. Something like (i'll use c# but I guess it's clear anyway)
MyCrudModelForSomeForm {
[MyWebFormField(Default = 42, Type = typeof(int), Name = "txtAmount")]
public int SomeInt { get; set; }
[MyWebFormField(Default = "Hello", Type = typeof(string), Name = "txtMessage", Validate = "$[A-Z]{6}^")]
public string SomeString { get; set; }
[MyWebFormField(Default = "Zimbabwe", Type = typeof(string), Name = "txtCountryChoice")]
public string SomeOtherString { get; set; }
}
That's basically the custom implementation of M(odel) from MVC concept.
The ASP.NET Webforms arch does not support multiple forms
If you have created a page that has multiple forms then i would suggest use jQuery and Post Individual form to the respected handler to process the request
This will be simple and elegant
On my current project I need to add a functionality that allows the user to view a thumbnail of their uploaded PDF. I've found a handy component that achieves this (the basic version is free, but it's enough for my current needs). Anyways, the control is pretty outdated (2010), therefore there doesn't seem to be MVC support. On the demos they depict usage of the control as such:
The View's Markup:
<form method="post" runat="server" enctype="multipart/form-data">
<asp:Panel ID="thumbnailsPanel" runat="server" />
</form>
The thumbnail control is instantiated via code, the byte array which represents the thumbnail is passed to the control and the control is added to thumbnailsPanel
<script runat="server">
protected void DisplayThumbs_Click( object sender, System.EventArgs e )
{
Thumbnail thumbnail = new Thumbnail();
thumbnail.SessionKey = sessionID;
thumbnail.Index = i;
thumbnailsPanel.Controls.Add( thumbnail );
}
</script>
Given that I can't declare a Thumbnail control in my razor view, how would I used this control in MVC? I've spent a few hours trying to make this control MVC friendly to no avail, the best I've come up with is to include a .ASPX view (not.cshtml) in my project and render the Thumbnail control on that view. Obviously this is not desirable.
So how would you go about using a ASPX server controls in MVC? Is the idea a bad one altogether and should not be practised?
I worked around it in a project of mine by reimplementing the control as a HtmlHelper. Assuming the control isn't too complicated then it should work for you too. Do this:
Dump the Control's source using Reflector
Massage the source so it actually compiles (as source from Reflector doesn't usually compile straight away)
Identify what state the control has. Convert the state from member properties into members of its own new ViewModel class.
Find the Render method and convert it to a HtmlHelper that uses ViewContext.Writer
For example:
public class FooControl : Control {
public String Message { get; set; }
public override void Render(HtmlTextWriter wtr) {
wtr.WriteLine("<p>");
wtr.WriteLine( message );
wtr.WriteLine("</p>");
}
}
Becomes this:
public class FooViewModel {
public String Message { get; set; }
}
// This method should exist in a static Extensions class for HtmlHelper
public static void Foo(this HtmlHelper html, FooViewModel model) {
HtmlTextWriter wtr = html.ViewContext.Writer;
wtr.WriteLine("<p>");
wtr.WriteLine( model.Message );
wtr.WriteLine("</p>");
}
I've got an ASP.NET web site that includes a usercontrol that's added programmatically to an ASP.NET web form, using this code:
var control = (Deal)LoadControl("Deal.ascx");
control.ImageFile = dealNode.SelectSingleNode("thumbnail").InnerText;
control.ProductName = dealNode.SelectSingleNode("product").InnerText;
control.PriceText = dealNode.SelectSingleNode("price").InnerText;
DealList.Controls.Add(control);
The Deal control is really simple:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="Deal.ascx.cs" Inherits="Deal" %>
<div class="deal">
<img id="DealImage" runat="server" class="dealimage" />
<div class="dealtext"><asp:Label ID="DealLabel" runat="server"></asp:Label></div>
<div class="dealprice"><asp:Label ID="DealPriceLabel" runat="server"></asp:Label></div>
</div>
with the code behind it:
public string ImageFile { get; set; }
public string ProductName { get; set; }
public string PriceText { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
this.DealImage.Src = "images/" + ImageFile;
this.DealLabel.Text = ProductName;
this.DealPriceLabel.Text = PriceText;
}
When I run up the web site in Visual Studio 2010, it usually works fine. However, every so often (usually after a check-in or restarting VS2010), it gives up and won't compile. I get the error:
The type or namespace name 'Deal' could not be found (are you missing a using directive or an assembly reference?)
The problem being the cast in the line:
var control = (Deal)LoadControl("Deal.ascx");
If I comment out the usercontrol's Page_Load code, recompile, then uncomment the code and recompile, everything's OK again.
Can anyone tell me what's going on?
Try adding a reference to the control inside the page markup :
<%# Reference Control="MyUserControl.ascx" %>
See here
I've based my work on Phil Haack's article here: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
I've also looked over several posts here on StackOverflow and I can't seem to derive an answer for my problem from them, though, they probably present a solution. I guess I need the bits broken down a bit more.
I'm attempting to get Model Binding working for a view whose Model is a complex type where one of the properties is a List of another complex type. Here are my objects:
public class Data
{
public Data()
{
Assessments = new List<AssessmentItem>();
}
public String Associate { get; set; }
public String Department { get; set; }
public String JobTitle { get; set; }
public int StartPeriod { get; set; }
public int EndPeriod { get; set; }
public List<AssessmentItem> Assessments { get; set; }
}
public class AssessmentItem
{
public long Index { get; set; }
public String Heading { get; set; }
public String Comments { get; set; }
}
I've attempting to use the EditorFor + control template solution that Haack's article presents. Here is my Index view (note that it is strongly typed against a single objects and not a List).
Here is the controller method that accepts the post (though, I wouldn't think that'd matter for the initial view generation):
[HttpPost]
public ActionResult Index(Data data)
{
return View(data);
}
As you can see, it doesn't do anything functional at this stage. It just redisplays the data that was posted.
Here is the editor template in the Shared/EditorTemplates folder.
(file name: AssessmentItem.ascx location:
Views/Shared/EditorTemplates)
<%# Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<Project.Models.AssessmentItem>" %>
<%# Import Namespace="Project.Models" %>
Assessment Item Heading: <%= Model.Heading %>
<%= Html.HiddenFor(model => Model.Heading) %>
<%= Html.HiddenFor(model => Model.Index) %>
<%= Html.TextBoxFor(model => model.Comments) %>
<%= Html.ValidationMessageFor(model => model.Comments) %>
My confusion is that I'm not sure how to specify the index for each AssessmentItem. Haack's article & code include several HtmlHelper extensions methods, which I've also included in my own code, but that didn't resolve the issue.
Here is my view's calling code (this used to use Html.RenderPartial in the loop, but I couldn't figure out how to bind back to the Model.Assessments list part of the Model):
<% for (int i = 0; i < Model.Assessments.Count; i++) { %>
Entering Loop
<% Html.EditorFor(m => m.Assessments[i] ); %>
<% } %>
I confess I have a pretty big knowledge gap here. I had only just broken the surface with ASP.NET MVC 1 before attempting ASP.NET MVC 2, though, the improvements seem worth it.
One thing that is very odd is that I can't seem to use the <%: %> syntax. Any time I do, I get several compile time errors. I can use the typical <% %> & <%= %>, though. I'm pretty stuck here so any comments would be appreciated. The code isn't throwing any errors. The page loads as if none were thrown as well. It's just the controls that should be generated via the Html.EditorFor statement aren't. The 'Entering Loop' text is printed twice so I know my list has AssessmentItem objects in it.
Thanks for any and all help.
No need of for loops. All that you need is:
<%= Html.EditorFor(m => m.Assessments) %>
This will automatically call your AssessmentItem.ascx editor template for each item in the Assessments collection of your model. So just make sure the controller initializes it to some value. It will automatically take care of generating correct names for the inputs in the editor template so that the model binding works.
<%: ... %> is an ASP.NET 4.0 only and is equivalent to <%= Html.Encode(...) %> but if you are using .NET 3.5 it won't be available to you. Notice also the absence of ; at the end of the EditorFor helper when used with <%= ... %>.