Posts

Showing posts with the label asp.net

MVC 4 - Dynamic Output

Image
The whole point of a Web application platform is to construct and display dynamic output. In MVC, it is the controller’s job to construct some data and pass it to the view, which is responsible for rendering it to HTML. One way to pass data from the controller to the view is by using the ViewBag object, which is a member of the Controller base class. ViewBag is a dynamic object to which you can assign arbitrary properties, making those values available in whatever view is subsequently rendered. Example below demonstrates passing some simple dynamic data in this way in the HomeController.cs file. HomeController.cs  public class HomeController : Controller     {         //         // GET: /Home/         public ViewResult Index()         {             int hour = DateTime.Now.Hour;             ViewBag.Greeting = hour < 12 ? "Good Morning" : "Good Afternoon";             return View();         }     } Index.cshtml @{ Layout = null; } <!DOCTYPE html> <html&g

MVC 4 - Rendering web Pages

Image
The output from the previous post wasn’t HTML—it was just the string " Hello World, This is my first MVC Application ". To produce an HTML response to a browser request, we need to create a view. Creating And Rendering a View Modify the Controller to render a View (please refer the previous post before you do this).         public ViewResult Index()         {             return View();         } Right click at word View() and choose Add View Leave the devault value and click Add button Congratulation, now you have successfully created new view which will be rendered as html when the root / or  /Home or /Home/Index url hit Note : The . cshtml file extension denotes a C# view that will be processed by Razor . Now copy this HTML code on the Index.cshtml file. @{     ViewBag.Title = "Index"; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head>

Creating Your First MVC 4 Application

Image
In this tutorial i will show the example on MVC 4. Follow this step to create new MVC Application on Microsoft Visual Studio 2010. Creating MVC 4 Project File >> New Project Choose ASP.NET MVC4 Web Application. (If you dont have MVC 4, Install it here ) On Project Template , choose Empty if you want to start from zero or choose Internet Application to start developement with default template. Choose View engine Razor. Click OK button Now you have create one project with MVC4 Solution  Adding First Controller Right click on the Controller folder under Solution Explorer Menu. Choose Add >> Controller Rename Controller Name to HomeController Since this is empty project, so under Scaffolding Options Template choose Empty MVC Controller Change The default ActionResult Index() like this         public string Index()         {             return "Hello World, This is my first MVC Application";         } Run the project, You should see the output on the browser lik

How to send email in ASP.NET- C# example

Image
This is example how to send email from asp,net web application. Refer this post if you want to send email in java code . This example will use google smtp email server. The aspx Page <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">     <asp:Label ID="LErrorMessage" runat="server" ></asp:Label>     <asp:Button ID="Button1" runat="server" Text="Send Email" OnClick="Button1_Click" /> </asp:Content> The Code Behind  protected void Page_Load(object sender, EventArgs e)         {         }         protected void Button1_Click(object sender, EventArgs e)         {                        string emailContent = "This mail is created and send through the c# code,"                     + "\n\n if you are developers, visit http://www.developersnote.com!",                     subject = "Developersnote update - Mail Send Using AS

[SOLVED] JQuery - AJAX 500 Internal Server Error - JSON - jQueryAjax

Image
The above error always occur if you work with jQuery + Ajax. The error above may have several reason why the error occur and one of the reason is you are using the different parameter name to post to the server. Let say the method getState in webservice require one parameter which will represent country name, you must use the exactly name parameter to request from webservice. The Other Reason Not using JSON.stringify to pass parameter value. If you not supply type in jQuery, it will use GET method which is not accept in your webservice configuration. Add  ( type : "POST ) in your jQuery code to use POST method. You are actually request data from different domain. Cross Domain Request (CORS)which is not allowed. Please read here Content type not supply or not correct. Use " application/json; charset=utf-8 " DataType not not supply or not correct. Use json or jsonp By Mohd Zulkamal NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Fa

How to add items list in dropdown list using jquery - Cascading drop down

If you want to create 2 dropdown lists in which the second dropdown value will depend on the selected value from the first dropdown, you need to Implement JSON + Webservice+ JQuery. In my solution, I will use Jquery Ajax to request data from web service and add value to the second dropdown. Scenario Let say the first dropdown will list all Country, and the second dropdown will list all state from the selected country. Solution Create JSON Webservice, you can refer to this link Create custom JQuery function to handle onChange event on dropdown list country. Use return value from web services to the second dropdown items list. Full Code Example Note: The web service will use from the post here <!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>     <title></title>     <script type="text/javascript&quo

How to create JSON webservice in ASP.NET

This example will show how to create Webservice using asp.net and the result will return in format JSON ( JavaScript Object Notation ). Below is the step by step to create webservice: Open Visual studio. Create New Project Add New File in the solution and choose Web Service file( .asmx) Copy paste code below to create your own JSON webservice The Web Service Code /// <summary>     /// Summary description for KenticoJSONTest     /// </summary>     [WebService(Namespace = "http://tempuri.org/")]     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]     [System.ComponentModel.ToolboxItem(false)]     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.     [System.Web.Script.Services.ScriptService]     public class AjaxWebService : System.Web.Services.WebService     {         [WebMethod]         public string HelloWorld()         {             return "Hello World";         }         [WebMethod]

Print GridView Header On Each Page While On Printing : ASP.NET

Image
This example will show how you can include Table header on each page when you print the html document. You need to have the css, and javascript to do this objective. Let see the full example. The ASPX Page <!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>     <style type="text/css" media="print">         .hideOnPrint         {             display: none;         }     </style>     <style type="text/css">         @media print         {             th             {                 color: black;                 background-color: white;             }             THEAD             {                 display: table-header-group;                 border: solid 2px black;             }         }     </style>     <sty

Multiple select button in one gridview

Image
GridView Multiple Select Buttons this is the keyword when i used to searching in Mr. Google and end up with several link to solve this problem. This was my solution to have a multiple select button in one GridView Controller The ASPX Page   <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical" Font-Names="Arial" Font-Size="12px" OnRowCommand="ActionCommand"> <Columns> <asp:BoundField DataField="ID" HeaderText="NO." /> <asp:BoundField DataField="CustomerName" HeaderText="Customer Name" /> <asp:ButtonField CommandName="showName" Text="Show Name" /> <

RegisterForEventValidation can only be called during Render()[SOLVED]

Today i do my routine by developing / testing / and debuggig and found error on my web page : RegisterForEventValidation can only be called during Render(); The code actually for get html code from server side inside panel ...  var sb = new StringBuilder();  Panel1.RenderControl(new HtmlTextWriter(new StringWriter(sb)));  string htmlToConvert = sb.ToString(); So i do some googling and found the causes of this error occur.. The Causes occurs when you try to render a control to Response. Generally some people got this when I exported GridView to Excel, Word, PDF or CSV formats. The ASP.Net compiler issues the above Exception since it feels the Event is invalid. Solution The solution is quite simple you need to notify ASP.Net that not to validate the event by setting the EnableEventValidation flag to FALSE You can set it in the Web.Config in the following way <pages enableEventValidation="false"></pages> This will apply to all the pages in your website. Else yo

Pinging in ASP.NET Example

Image
This tutorial will show you how to ping a hostname/ip using the .NET System.Net class, ASP.NET 2.0 and C#.NET. The .NET Framework offers a number of types that makes accessing resources on the network easy to use. To perform a simple ping, we will need to use the System.Net, System.Net.Network.Information, System.Text namespaces. using System.Net; using System.Net.NetworkInformation; using System.Text; ASPX Page  <asp:ScriptManager ID="ScriptManager1" runat="server">     </asp:ScriptManager>     <asp:UpdatePanel ID="UpdatePanel1" runat="server">         <ContentTemplate>             <table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#cccccc">                 <tr>                     <td width="100" align="right" bgcolor="#eeeeee" class="header1">                         Ho

Dynamically Add/Remove rows in HTML table using JavaScript

Image
This is very often for web developer when we need to use dynamically generate HTML table using JavaScript. The example will spare the first row(cannot delete) and you can dynamically add new row by clicking the button Add Row or delete the row by clicking the button Delete Row . The Code <!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>     <title>Add/Remove dynamic rows in HTML table </title>     <script language="javascript">            function addRow(tableID) {             var table = document.getElementById(tableID);             var rowCount = table.rows.length;             var row = table.insertRow(rowCount);             var cell1 = row.insertCell(0);             var element1 = document.createElement("input");             element1.type = "checkbox";             ce

How to remove a MenuItem base on condition

There may be an easier solution, which is to use the MenuItemDataBound event. I use this to hide menu nodes from the Menu Controller . Keeping them in the siteMap allows them to appear in the Menu Controller , but I don't want them in the Menu Controller based on the Roles attribute . Here's my code: The SiteMap File <?xml version="1.0" encoding="utf-8" ?> <siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >     <siteMapNode url="" title=""  description="">         <siteMapNode url="#" title="Home" roles="*"  description="This is Homepage" />         <siteMapNode url="" title="About" roles="*"  description="This About Page" />         <siteMapNode url="_#" title="Product" roles="ADMIN" description="This is Product Page, Only Role Admin Can access"

ASP.NET - MSSQL Server Database Timeouts

Image
One of the most disturbing aspect of most database applications is connection timeouts. Most of us might have faced this at one time or other. It would be helpful if we have complete control over the timeout and execution of our database queries/procedures. There are 3 different places that you need to check if you face a timeout in your application. Let us say, you have an application that runs a lengthy stored procedure and you started getting a timeout error. You tried to optimize the procedure to the maximum possible extend. At this stage, it is desirable to have a way to extend the timeout so that the user will see the results even after waiting for a little longer. Database Timeout Settings The first place that you need to check is your database server, to see if the server accepts long running queries/procedures. You can do this by checking the properties of the database. If you are using enterprise manager right click on the server name and select properties.

Configure IIS 7.5 to manage ASP.NET 4.0 web pages

Image
Problem Solution After installing .NET Framework 4.0 on a machine there is a few configuration changes you need to do to IIS in order to get a ASP.NET 4.0 page running. First set the Application pool to run in ASP.NET v4.0 “mode”. Then you need to allow ASP.NET v4.0.x to run. This is done in the ISAPI and CGI Restrictions found on the server level. Follow The picture below to make it done.. 1) 2 ) 3) 4) Select the same version you have installed on your server, (32 bit or 64 bit). And change to Allowed.  By Mohd Zulkamal NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

Arranging DIVs Horizontally

Image
Working with DIV tag is always problem and hard work thats why many web developers avoid creating their websites in DIV tag, in this tutorial, I will show you how to arrange DIVs in horizontal order with CSS. The HTML Code This is the html code for 4 divs div.container, div.left, div.middle and div.right. Note: Below the div.right there is another div with height:0; and width:100% and clear:both, the job of this div is to make sure the floating divs not going outside the container, try on your own to remove the div.clear to see what will happen on those floating div.    <div class="container">    <div class="left">Left</div>    <div class="middle">Middle</div>    <div class="right">Right</div>    <div class="clear"></div>    </div> The CSS Code .container{ width:600px; padding:0; border:5px solid #ddd; margin:0 auto; } .left{ float:left; width:150px; height:300px; te

Google Map API Zoom The Marker Example

Image
Google Map API Marker is a powerful API to use for web page to mark on the map for example the location of your business office. This tutorial can use in all framework as long as the framework use html language to render the content to client side. You can refer here for more information of Google Map API Let see the example in asp.net framework. The Javascript to call map and marker var map; function initializeGMap() {            var Centre = new google.maps.LatLng(3.15681, 101.714696);             var mapOptions = { zoom: 12, center: Centre, mapTypeId: google.maps.MapTypeId.ROADMAP };             map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);             var KLCC = new google.maps.LatLng(3.15681, 101.714696);             var marker = new google.maps.Marker({ position: KLCC, map: map, title: 'Kuala Lumpur City Center' });          }         google.maps.event.addDomListener(window, 'load', initializeGMap); The Zoom Marker Script fu

XMLHttpRequest Example with Webservice asp.net

Image
AJAX is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. If you want to retrieve information from server side and you do not want to fully post the entire page to the server side, you need to use ajax in your web page. This post show example how to use simple XMLHttpRequest Object in your web page to get the information from server side. The Javascript AJAX  <script type="text/javascript">         function createXHR() {             if (typeof XMLHttpRequest != "undefined") {                 return new XMLHttpRequest();             } else if (typeof ActiveXObject != "undefined") {                 if (typeof arguments.callee.activeXString != "string") {                     var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0",                      "MSXML2.XMLHttp"];                     for (var i = 0, len = versions.length; i < len; i++) {