I am new in developing using asp.net.
I use java(struts2) to do the web application before,it is easy to control this use the jsp tag or struts2 tags:
For example(suppose the "do something" operation need use login):
<s:if test="#session.user!=null">
<span>do something</span>
</s:if>
So if a user did not login,he will never see the menu of "do something".
Now I wonder how to make it in the asp.net?
Is this controled in the xx.aspx.cs?
Thanks.
There are several ways to handle "membership" in asp.net. Microsoft has the Membership Provider as a built in solution. It seems however you have gone with a failrly simple one of your own devising.
You could handle your problem two ways using what you've already got.
In the aspx page you could have:
<% if(Session["user"] != null) { %>
<span>Do Something</span>
<% } %>
Preferably move the logic to the code behind page (.aspx.cs)
In your aspx page have
<span id="thisSpan" runat="server">Do Something</span>
Then in yout code behind page in the onPage Load event
thisSpan.Visible = Session["user"] != null;
Related
I have a kendo single page application that I need to localize. I tried using Javascript to translate text parts, but it gets complicated when translating non HTML bits like templates (inside script tags) and properties like "data-title".
Next I tried changing the extension to .aspx and using ASP.NET resources, as in this example:
<!-- logout -->
<div id="logout" data-role="view" data-layout="layout-logout"
data-title="<asp:Literal ID="Literal1" runat="server" Text="<%$ Resources:TextStrings, Logout%>" />"
data-before-show="myproject.logout">
<div style="padding: 50px 0; text-align: center;">
<p id="lang_LoggedOut"><asp:Literal ID="Literal2" runat="server" Text="<%$ Resources:TextStrings, Logout_Success%>" /></p>
</div>
</div>
This works to some extent, as the <% resources %> bits get replaced.
However I had to transfer login to a separate .aspx page to apply the language, after login (and discovering user culture), but before single page app load.
The login page calls the customary:
protected override void InitializeCulture()
to set the culture, and then redirects to the main app page.
As far as I can make out, the InitializeCulture is ignored, but the page is rendered with the strings from the resource files, sometimes in one language, sometimes in another.
How does ASP.NET decide what culture to apply, and how can I control that choice?
Notes:
failing this, the kendo people seem to suggest having one page for each language, which rather goes against my DNRY inclinations.
Code behind and inline code (<%Page%> directive) are in my experience incompatible with kendo. If I understand right page events get stolen by one another. Kendo is compatible with MVC, but I must learn MVC first, and then get resource files to work with MVC.
The short answer is yes. I have seen it work with VS2010 and IIS 7.5.
The page with no code behind must have an .aspx extension.
the language selection must happen on another .aspx page with code-behind. Call InitializeCulture() here
from this page you must go to the main page using Server.Transfer. See: Server.Transfer Vs. Response.Redirect
Server.Transfer will keep the settings and context you set, and apply the language to the page with no code-behind while the user navigates the page.
I am having a bootstrap problem I hope one of you might have a solution to.
I have placed all my JavaScript references in the bottom of my masterpage. This usually works fine, but now I have a ASCX control which needs to add some JavaScript too the footer (initialization of a module). The reason why I can't initialize the module from the master page is because I need some properties from my codebehind file.
In ASP.NET MVC I would have used sections to inject data from a usercontrol to a section in the masterpage, but is this even possible in ASP.NET Webforms 4?
No, that concept of sections in not available in WebForms.
One way to do what you've described is to use the <%= %> syntax and send the values of server properties to the client (HTML output). In your ASCX control you can have the following markup:
<script type="text/javascript">
var clientProperty = <%= MyServerProperty %>;
</script>
ASP.NET WebForms will substitute the value of MyServerProperty above when it renders the page, and then you can access clientProperty as a global variable from the script in the masterpage.
Another approach is to use a Hidden field and set its value on the server. It will be rendered as an <input type="hidden">, whose value you can then get from any script by ID.
A third option is to load the actual client script only from the ASCX control (when it makes sense), rather than put it in the masterpage (when it will be loaded everywhere in the site).
You could add something like this to the bottom of your master page:
<asp:PlaceHolder runat="server" ID="javascriptSection" />
Then in your page's code behind or in a <% %> tag:
var scriptTag = new HtmlGenericControl("script");
scriptTag.Attributes["type"] = "text/javascript";
scriptTag.InnerHtml = #"function () { ... }";
var javascriptSection = this.Page.Master.FindControl("javascriptSection");
if (javascriptSection != null)
javascriptSection.Controls.Add(scriptTag);
I'm using ASP.NET MVC 3 with the Razor template engine for my website. I currently allow files uploads like this:
<form action="/File/Upload" method="post" enctype="multipart/form-data">
<label for="file">Upload a file:</label>
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
But would like to use a 3rd party control such as NeatUpload, which allows a progress bar, multi file selection, etc.
In the documentation, they show the control being used like this:
<%# Register TagPrefix="Upload" Namespace="Brettle.Web.NeatUpload"
Assembly="Brettle.Web.NeatUpload" %>
<Upload:InputFile id="inputFileId" runat="server" />
with some code-behind.
The Razor engine understandably doesn't like this syntax. Is there another way to use 3rd party controls with it, or am I out of luck?
Third party controls that work with Web Forms aren't really compatible with a pure MVC application. Having said that, you may be able to work with a hybrid type of solution, leveraging Web Forms in certain places and MVC in others. It's not something I would do personally, but you could.
See this post by Scott Hanselman which goes into some detail about doing just that.
Using a web forms control on a Razor page just won't work though.
Specifically for NeatUpload (which is amazing!) there is now the ability to get the uploading of very large files using javascript on a static HTML page. Clearly this will work just as well with MCV whatever view engine you use :)
http://www.brettle.com/NeatUpload-1.3/dotnet/docs/Manual.html#3.11.Using%20NeatUpload%20from%20JavaScript%7Coutline
So more general solution "ask the developer of the user control to update to an MCV compatible version"
Edit: I won't change the above but note that NeatUpload is now hosted http://neatupload.codeplex.com/ but maybe dead (why not pick it up if you have the developer skills and time!)
The Razor view engine does not support WebForms controls. You will need to find a library that is specifically designed to work with MVC.
I just found that the MVCRecaptcha project that appears to be doing exactly this. I haven't had the time to dig through the internal details, but the essence is contained in two small files. For those of you too lazy to follow the above link, let me try to explain:
Basically, they create the control programmatically, then call RenderControl to dump the html on the wire:
var captchaControl = new RecaptchaControl { ... }
var htmlWriter = new HtmlTextWriter(new StringWriter());
captchaControl.RenderControl(htmlWriter);
return htmlWriter.InnerWriter.ToString();
On the response side, they then create an attribute that you can add to your MVC actions:
class CaptchaValidatorAttribute : ActionFilterAttribute {...}
This class that re-creates the control, and calls:
var recaptchaResponse = captchaValidtor.Validate();
// this will push the result value into a parameter in our Action
filterContext.ActionParameters["captchaValid"] = recaptchaResponse.IsValid;
Which means that your controller will have to look something like this:
[CaptchaValidator]
[AcceptVerbs( HttpVerbs.Post )]
public ActionResult CreateComment( Int32 id, bool captchaValid )
{
if (!captchaValid)
{
ModelState.AddModelError("_FORM", "You did not type the verification word correctly. Please try again.");
}
// ...
}
Although the project is now obsolete, it shows how to use an ASP.Net control in an MVC application.
You can do this, assuming you just want a render of the control content and don't care about registering scripts or postbacks, etc.
Create your own HtmlTextWriter, write the output to it, and then render that string in your Razor. This is basically the idea from #VeeTheSecond, reduced to practice:
#{
System.Web.UI.WebControls.Label label = new System.Web.UI.WebControls.Label()
{
Text = "Hello World!"
};
HtmlString renderedControl;
using (StringWriter w = new StringWriter())
{
using (HtmlTextWriter htmlW = new HtmlTextWriter(w))
{
label.RenderControl(htmlW);
renderedControl = new HtmlString(w.ToString());
}
}
}
<div>
#renderedControl
</div>
Try placing the control in a <form runat="server"> tag.
page1.aspx
<input type="text" runat=server id="text1"/>
page2.apx
protected void btnCreateMember_Click(object sender, EventArgs e)
{
text1.text="test";
}
How can I change Input on Page1.aspx through Page2.aspx Method btnCreateMember_Click
I think that you are missing some very basic concepts about ASP.NET MVC here. In ASP.NET MVC there is no such thing as runat="server", nor any callbacks. There is no ViewState nor PostBacks. Even if it is based on ASP.NET, ASP.NET MVC is a fundamentally different framework. In ASP.NET MVC you have Models, Controllers and Views. So if you want to send values from one view to another controller action you could use a form with HTML helpers:
<% using (Html.BeginForm("someAction", "someController")) { %>
<%= Html.TextBoxFor(x => x.SomeProperty) %>
<input type="submit" value="OK" />
<% } %>
I would recommend you going through the tutorials here: http://asp.net/mvc to familiarize yourself with the basic notions of MVC.
I see the MVC tags have been removed.
This isn't how webforms work.
If the user is on Page 2 and clicks the "Create Member" button, then you should perform the logic to "create a member" there and redirect as necessary.
If you redirect from Page2 to Page1.aspx, then the page_load event of Page1.aspx should load whatever data it needs and populate any necessary page controls itself.
In other words, each page should be encapsulated to pull, display, and update the data it needs.
I have a web application that has a page that loads the content from the database. I want to be able to put a form in the dynamic content, but .net doesn't let the inside form perform it's action. Is there a way to allow this or some other way I can get a form on a dynamic content page?
--EDIT--
I think I need to clarify something. This is an aspx page that loads content from the database. As far as I know, the text I pull from the db and stick in the Label is never compiled or processed by the .net wp, thus I can't use the code behind to fix this issue.
This is a common problem, when you want to have a non-postback form to a 3rd party site (like a PayPal button, for example).
The problem occurs because HTML doesn't let you have form within a form, and most ASP.NET pages have a <form runat="server" /> "high up" in the HTML (or in the Master page).
My favorite solution is to hide the "high up" form tag, while still showing all of the content. Then you can feel free to dump any tags you want in the body. If you do this dynamically you can choose on a page-by-page basis which pages have custom forms.
I created a class called GhostForm.cs to handle this. You can read all about it here:
http://jerschneid.blogspot.com/2007/03/hide-form-tag-but-leave-content.html
There can only be one form on the page (the asp form); you have to use that form somehow.
To clarify, there can only be one form processed.
Not with webforms, no. You have to work within the one, full page form by using an event handler connected to a Button to LinkButton. Fortunately, it's pretty easy to do:
foo.aspx:
...
<asp:TextBox id="txtFoo" runat="server" />
<asp:Button id="btnFoo" runat="server" onclick="btnFoo_Click />
...
foo.aspx.cs:
...
protected void btnFoo_Click(object sender, EventArgs e)
{
string s = txtFoo.Text;
// do something with s
}
...
Dino Esposito has an article from MSDN magazine that covers handling multiple forms or "simulating" sub forms in ASP.Net that might just answer all your questions.
http://msdn.microsoft.com/en-us/magazine/cc164151.aspx
Any work around would be hacky and very ugly. By design asp.net uses a form tag to post and get data. This is why they call it a Web Forms Application. Html does not allow nested forms. What you want to do is use a WebRequest in your code behind.
If you are trying something like a paypal button you could simply use something like this.
Markup:
<div id="PayPalButtonContainer" runat="server"></div>
Code Behind:
public static string GetPayPalButtonMarkup()
{
const string markup = #"https://www.paypal.com/cgi-bin/webscr
?cmd=_xclick&business={0}
&item_name=Widget
&amount={1}
¤cy_code=USD";
return markup;
}
PayPalButtonContainer.InnerHtml = string.format(GetPayPalButtonMarkup,"YOUR PAYPAL USER NAME", "YOUR PRICE VALUE");
you either have to deal with the postback by adding a server side click event handler to what you want to be the "sub forms" submit button (this is how web formas deals with multiple submit type buutons on the same page) or do soemthing clever with AJAX if you dont want a full post back
I've run across this issue before. One workaround that I have done is to place my code that I want my action to be done upon inside of an asp:Panel. With the panel you can set the attribute of "DefaultButton" to a button inside of the panel, and clicking the button (or pressing "enter") will fire that button's click event. I've found this quite handy when wanting to submit a "form" by pressing enter when I have a master page that contains the only allowable asp:Form.
Hope this helps.
When I first came across this problem, I found the simplest solution for me was to simple COPY and PASTE the Master page and give it a slightly different name, something like:
SiteNameMasterPage 'Default page with FORM tag
SiteNameMasterPageNF 'No Form tag
And then depending on wether I wanted a FORM tag or or not, simply change the masterpage link at the top of my CONTENT-PAGES, like this
<%# Page Title="" Language="VB" MasterPageFile="~/SiteName.master" %>
<%# MasterType VirtualPath="~/SiteName.master" %>
<!-- This masterpage has the default FORM tag -->
or
<%# Page Title="" Language="VB" MasterPageFile="~/SiteNameNF.master" %>
<%# MasterType VirtualPath="~/SiteNameNF.master" %>
<!-- This masterpage does NOT have the default FORM tag -->
and then in the content page, wherever I want to place my form I can include the <form> tag