Showing posts with label MVC 3. Show all posts
Showing posts with label MVC 3. Show all posts

Friday, July 20, 2012

How To call Mvc Function With Json



    $(document).ready(function () {
        $("#ddlModelSeries").change(function () {

            var Mname = $(this).val();

            $.getJSON("AddModelSeries/LoadBrand", { id: Mname }, function (AreaData) {
                var select = $("#ddlBrand"); select.empty(); select.append($('
                $.each(AreaData, function (index, itemData) {

                    select.append($('
                        value: itemData.Value,
                        text: itemData.Text
                    }));
                });

            });

        });


    });

             



how to hide menu in mvc 3 on master page





@if(Session["username"] !=null)
    {
 

 
     
 @Html.ActionLink("Manange Step", "Index", "Adminmanage")
 &nbsp 
@Html.ActionLink("Manange Errorcode", "Index", "Admin")&nbsp&nbsp

 @Html.ActionLink("LogOut", "LogOn", "Account")&nbsp&nbsp
     

        }

how pass value from page to javascript with hidden varible


@model UFixnow.Models.ModelSeries
@{
    ViewBag.Title = "Index";
   Layout = "~/Views/Shared/_Adminlayout.cshtml";
    var id = Session["SeriesId1"];
}





Monday, January 9, 2012

how we add sitemap in mvc3


Once you’ve got your sitemap correctly configured and setup, you will be looking to use some of the features of a Sitemap – for example, breadcrumbs. In this post we will start with an empty MVC3 project, and add the asp.net sitemap provider, a few controller actions and corresponding views, and we will have the provider produce some breadcrumbs for us.

Setup

Lets start from an Empty MVC3 project. Fire up Visual Studio. Create a new Asp.Net MVC3 Web application. I’m going to call mine SitemapDemo:
Create new MVC3 project
For the sake of this demonstration, I have selected an empty template and have chosen Razor as my view engine.
Now before we go any further, lets go ahead and install the NuGet package.  Select View > Other Windows and then select “Package Manager Console”:
Package Manager Console Location VS2010
This will then dock the Package Manager Console somewhere into your view. In order to add the Asp.net MVC sitemap provider to the current project, we need to enter the following command into the Package Manager Console, and hit enter:
PM> Install-Package MvcSiteMapProvider
This command will then download the necessary files (dlls, cshtml files) and add them into your MVC project. This could take a few minutes depending on your connection. If this has been successful, your Package Manager Console should give you an output similar to the following:
PM> Install-Package MvcSiteMapProvider
Successfully installed 'MvcSiteMapProvider 3.1.0.0'.
Successfully added 'MvcSiteMapProvider 3.1.0.0' to SitemapDemo.

PM>

Now lets take a look at what exactly the NuGet package manager has added to our project:
  • SitemapDemo > References > MvcSiteMapProvider – This is the reference to the MvcSiteMapProvider dll
  • SitemapDemo > Mvc.sitemap – This file will be used to describe our MVC3 website in XML nodes
  • SitemapDemo > Views > Shared > DisplayTemplates > MenuHelperModel.cshtml
  • SitemapDemo > Views > Shared > DisplayTemplates > SiteMapHelperModel.cshtml
  • SitemapDemo > Views > Shared > DisplayTemplates > SiteMapNodeModel.cshtml
  • SitemapDemo > Views > Shared > DisplayTemplates > SiteMapNodeModelList.cshtml
  • SitemapDemo > Views > Shared > DisplayTemplates > SiteMapPathHelperModel.cshtml
  • SitemapDemo > Views > Shared > DisplayTemplates > SiteMapTitleHelperModel.cshtml
As we’re using Razor as our view engine, we can go ahead and delete the asax files that have been added to the SitemapDemo > Views > Shared > DisplayTemplates folder. Here’s how your solution should now look:
Sitemapdemo Solution Explorer
Now that’s the install over. Let’s add a half decent set of controller actions and views to the site before we go on to playing with the SiteMapProvider. The point of this is to capture the kind of structure that you would find in a typical website.
Important
The MVC Sitemap provider will fail silently in some fashion if we try to force it to work with controller actions that either don’t exist or that point to non existent views. This is why we are doing this stage first.
All sites have a homepage, so lets add this first. Right click on your Controllers folder, and add a controller called “HomeController”. Lets leave the scaffolding options blank:
HomeController-Add Blank
Once your controller is created and open, right click inside the Index action and select “Add View…”
Home Index Add View
In the Add View dialogue that pops up, just go a head hit add. Nothing will need changing.  Now lets change the text inside the created page’s h2 tag on the page – something like “Index – this is the home page” will do.
And now lets add another controller in the same way that we added the HomeController. Let’s call it NewsController. Update the newly created news controller to contain an additional action result called “Sports”:

01using System;
02using System.Collections.Generic;
03using System.Linq;
04using System.Web;
05using System.Web.Mvc;
06
07namespace SitemapDemo.Controllers
08{
09    public class NewsController : Controller
10    {
11        //
12        // GET: /News/
13
14        public ActionResult Index()
15        {
16            return View();
17        }
18
19        //
20        // GET: /News/Sports/
21        public ActionResult Sports()
22        {
23            return View();
24        }
25
26    }
27}

Now, lets add a view for each of our newly created NewsController actions. Lets do this in the same way that we added the view for the home page – by right clicking within the body of each controller action. Again, we can simply leave all of the defaults in the “Add View” dialogue and just hit “Add” for both views.
Now edit the h2 tag on the News Index cshtml file to read “News Index”. Lets also edit the h2 tag on the News Sports cshtml file to read “Sports News”.
Let’s now add one more Controller for illustration – AboutController. Once created, you can leave the controller unchanged, and can add a view for the Index controller action. This time, lets change the h2 to tags to read “About Page”.
As we have now added 4 pages to our website, it’s now worth just testing them out before we start integrating the Site Map Provider. Hit the debug button – below are screen shots and their corresponding URLs:
localhost:xxxx
SitemapDemo Index
localhost:xxxx/News
SitemapDemo News Index
localhost:xxxx/News/Sports
SitemapDemo News Sports
localhost:xxxx/About
SitemapDemo About Index
Ok, so we’ve now got a small site with a little bit of a structure. Lets represent that structure in an easy diagram:
SitemapDemo Sitemap Diagram
Visualising our layout like this will really help us describe our site’s structure in our Mvc.sitemap file correctly. Our Index page is our wrapper for the entire site as it is the page that sits in the root, and is the first port of call into the site.
Now lets get into configuring our Sitemap. Lets start by editing our Mvc.sitemap file, which is in the root of our project. This file contains all of the xml nodes needed to represent your controller and action combinations.
MVC Sitemap xml file vs
Edit your Mvc.Sitemap file so that it is the same as the listing below:

1xml version="1.0" encoding="utf-8" ?>
2<mvcSiteMap xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-3.0" enableLocalization="true">
3  <mvcSiteMapNode title="Home" controller="Home" action="Index">
4    <mvcSiteMapNode title="News" controller="News" action="Index">
5      <mvcSiteMapNode title="Sports News" controller="News" action="Sports"/>
6    mvcSiteMapNode>
7    <mvcSiteMapNode title="About" controller="About" action="Index"/>
8  mvcSiteMapNode>
9mvcSiteMap>

We have now represented our website structure / workflow in the MVC.Sitemap file. A classic “gotcha” here is forgetting that your entire site is wrapped in a node that represents your homepage. Your sitemap file must contain this node – after all, your website’s homepage is the page that the client sees as the root of everything. So even though the Index action is actually at yourwebsite/Index, the client will typically see it just as yourwebsite/. The rest of the structure should make sense when compared to the website navigation diagram, earlier in this post.

Adding Navigation

Now that we’ve got some controllers and actions setup, and our site structure described properly in our Mvc.Sitemap file, lets add some navigation to all pages.
Open up your _Layout.cshtml partial, located in the Views/Shared folder. Update the listing so that the code between the body tags looks like this:

1<body>
2    @Html.MvcSiteMap().Menu(false, true, true)
3    @RenderBody()
4body>

We are now calling the MvcSiteMap library and telling it to output the website’s navigation on every page. The parameters specified mean that:
  • We don’t want it to start from the current node (changing this to true will break it!)
  • We want the starting node to appear in child level
  • We want to show the starting node. Setting this to false will hide the parental “Home” node
And now if we run our application, we should see the navigation laid out on every page, complete with links:
Index with navigation

News with navigation

Editing the navigation appearance

So now we’ve managed to output a simple navigation onto all pages of our website. If you want to change any styling, or how the navigation is displayed, simply alter the code in Views/Shared/DisplayTemplates/MenuHelperModel.cshtml. Lets make a simple change and add an inline style to change our bullet points from circles to squares:

1<ul>
2    @foreach (var node in Model.Nodes) {
3        <li style="list-style-type:square;">@Html.DisplayFor(m => node)
4            @if (node.Children.Any()) {
5                @Html.DisplayFor(m => node.Children)
6            }
7        li>
8    }
9ul>

You can now hit refresh in your browser without needing to re-compile. Your News index page should now look like this:
News Index Square Bullets

Breadcrumbs

We can add breadcrumbs in a similarly easy fashion. Let’s open up our _Layout.cshtml partial and edit the listing:

1<body>
2    @Html.MvcSiteMap().Menu(false, true, true)
3    <p>Start of Breadcrumbs:p>
4    @Html.MvcSiteMap().SiteMapPath()
5    @RenderBody()
6body>

Now all pages on our site will have a handy set of breadcrumb links:
News Breadcrumbs MvcSitemap
Sportsnews breadcrumbs MVCSitemap
Similarly, if we want to customise the presentation of our breadcrumbs, we need to change the Views/Shared/DisplayTemplates/SiteMapPathHelperModel.cshtml file.

Dynamic URLs / Parametered URLs

Every real site will need to employ a dynamic / Parametered URL at some point. Incorporating a dynamic URL into the MVC Sitemap is straightforward when you know how. Lets start by adding a new action to the NewsController:

1//
2//GET: News/Article/x
3public ActionResult Article(int id)
4{
5    ViewBag.id = id;
6    return View();
7}

Now lets add a view – right click anywhere within the new action and select “Add View…”. Again, just hit Add – we don’t need to change any of the options. Now update the newly created Article.cshtml file with the following:

1@{
2    ViewBag.Title = "Article";
3}
4
5<h2>Viewing Article @ViewBag.idh2>

Now lets browse to localhost:xxxx/News/Article/1234:
News Article 1234 mvcsitemap
Note that this new page does not appear anywhere in our sitemap, and that the breadcrumbs are totally empty.
In order to add the page into our navigation, we must first decide where it needs to go. I’d like this page to sit underneath the News section. So lets edit our Mvc.Sitemap file and add a Key attribute to the “News” node. This is simply to give it a unique identifier:

1<mvcSiteMapNode title="News" controller="News" action="Index" key="News">

Now we need to decorate our controller action with some attributes that tell it where to insert the action in the site’s structure. Update your Article action in your News controller:

1//
2//GET: News/Article/x
3[MvcSiteMapNode(Title = "Article", ParentKey = "News")]
4public ActionResult Article(int id)
5{
6    ViewBag.id = id;
7    return View();
8}

Now lets compile and browse to localhost:xxxx/News/Article/1234:
Article Dynamic MVCSitemap

Wednesday, December 7, 2011

Calling web service using javascript.

Many a times there was this pressing need where I had to call a web service method and get the output and use it in javascript. There were many options available like making use of javascript to call web service method or using some third party javascript library or by making use of webservice behavior (HTML Component (HTC) file) or making use of AJAX and calling an ASPX page which in turn calls a webservice in the code behind and returns the output as XML or if you are using ASP.NET 2.0 then you can make use of “ScriptManager”. We will see all the above ways of invoking a webservice one by one except making use of third party javascript library. As there are many third party javascript libraries available in the internet so we will not concentrate on any as each have different ways of implementation.  Lets see each of the methods in action one by one.
Using javascript to invoke web service methods
One of the simplest and easiest way is to invoke web service methods is by making use of “XMLHttpRequest” objects in javascript. Before invoking the web service method using javascript lets see the web service methods which we are going to be invoked using javascript. Below are two sample methods which we are going to be invoked using javascript.
public class TestService : System.Web.Services.WebService
{
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public string CombineName(string firstName, string midleName, string lastName)
        {
            return string.Concat(string.Concat(firstName, " - ", midleName), " - ", lastName);
        }
}
The above two methods are pretty straight forward, one returns a string and the other takes three string arguments and combines them and returns as a string. We will see how to call a web service method without parameters and with parameters. Lets first see how to call the “HelloWorld” web method which doesn’t take any parameter. Below is the javascript code for invoking the “HelloWorld” web method.
function webServiceCallWithoutParameters()
{
        var xmlHttpReq = new XMLHttpRequest();
        xmlHttpReq.open("POST", "http://localhost/TestService.asmx/HelloWorld", false);       
        xmlHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlHttpReq.send();       
        alert(xmlHttpReq.responseXML.childNodes[1].text);
}
In the above javascript function we are making use of “XMLHttpRequest” object to invoke web service method. We are making use of the “open” method which takes three arguments, first argument says whether the method used is “POST” or “GET”, second argument is the url for the web service and the third argument is to specify whether the “XMLHttpRequest” should be synchronous or asynchronous. The url for a .NET web method always ends with the name of the web method preceded by the url of the web service as shown in the above e.g. Once we have set the url and the method used to call the web service, in the next line we are setting the “Content-Type” for the request using the “setReqeustHeader” method of the “XMLHttpReqeust” object. Its very important to set the “Content-Type” of the request to “application/x-www-form-urlencoded” when you are trying to invoke a web service method, if the “Content-Type” is not set to “application/x-www-form-urlencoded” the following error will be thrown when you try to pass arguments to a web service method.
status: 500
statusText: Internal Server Error
responseText: System.InvalidOperationException: Request format is invalid: . at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
The status property of the “XMLHttpReqeust” object will have a value of 500, the “statusText” will be having “Internal Server Error” as the message and the “responseText” will have the type of error. To solve the problem set the “Content-Type” for the request as shown in the above e.g.
Now let’ see how to pass parameters to a web method.
var xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open("POST", "http://localhost:3150/TestService.asmx/CombineName", false);
xmlHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpReq.send("firstName=Sandeep&midleName=mid&lastName=p r");
alert(xmlHttpReq.responseXML);
In the above javascript function we are invoking the “CombineName” web method which takes three parameters. Everything else is the same as the previous javascript function except for the “send” method of the “XMLHttpReqeust” object. In the “send” method we are passing the parameters separated by the ampersand (&) symbol. To pass parameter to a web method you can use the “send” method of the “XMLHttpRequest” object. The parameters and their values should be separated by the “equal to” (=) symbol and each set of parameters should be separated by the ampersand symbol.
After this the next obvious question would be how to send complex objects to a web methods. There is no straight forward way of doing this, one can make use of Javascript Object Notations (JSON). You can find lots of e.g. on how to pass JSON over the net. Also you can use “WebService” behavior (HTC file) to send and receive complex objects or one can use “ScriptManager” to send and receive complex objects. We will see “HTC file” and “ScriptManager” usage in subsequent blogs. Receiving a complex object is pretty easy. When you invoke a web method and if that web method returns a complex object then the object will be serialized into a XML and the XML can be accessed through the “responseText” or “responseXML” property of the “XMLHttpRequest” object. Lets see with an e.g. Below is the web method code which returns a “Car” complex object.
[WebMethod]
public Car GetCarObject()
{
     return new Car { Model = "Ferrari", Color = "Ferrari Red", CC = 2555 };
}
//Car Class is pasted below.
public class Car
{
    public string Model
    {
        get;   set;
    }
    public int CC
    {
        get;   set;
    }
    public string Color
    {
        get;   set;
    }
}
The above web method is pretty straight forward. It creates an instance of a “Car” class and returns the same. The “Car” class is also pasted. The javascript method to invoke the above web method which returns “Car” complex object is pasted below.
function getComplexObject()
{
    var xmlHttpReq = new XMLHttpRequest();
    xmlHttpReq.open("POST", "http://localhost:3150/TestService.asmx/GetCarObject", false);
    xmlHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlHttpReq.send();
    alert(xmlHttpReq.responseText);
}
The output returned in the form of the XML is pasted below.

http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
  Ferrari
  2555
  Ferrari Red
As you can see in the above XML the complex object returned by the web method is serialized as XML. That's about invoking web methods using javascript

Friday, December 2, 2011

How to set startup page for debugging in asp.net mvc aplication?

Go to your project's properties and set the start page property.
  1. Go to the project's Properties
  2. Go to the Web tab
  3. Select the Specific Page radio button
  4. Type in the desired url in the Specific Page text box
  





Thursday, December 1, 2011

New HTML 5 input types in ASP.Net 4.5 Developer Preview

Microsoft has released developer previews for Visual Studio 2011 and .Net framework 4.5. There are lots of new features available in the developer preview. One of the most interested things for web developers is the support introduced for new HTML 5 form controls.
The following are the list of new controls available in HTML 5
  • email
  • url
  • number
  • range
  • Date pickers (date, month, week, time, datetime, datetime-local)
  • search
  • color
Describing the functionality for these controls is not in the scope of this article. If you want to know about these controls, refer the below URLs
http://msdn.microsoft.com/en-us/magazine/hh547102.aspx
http://www.w3schools.com/html5/html5_form_input_types.asp
ASP.Net 4.5 introduced more possible values to the Text Mode attribute to cater the above requirements. Let us evaluate these. I have created a project in Visual Studio 2011 developer preview, and created a page named “controls.aspx”. In the page I placed on Text box control from the toolbox
clip_image001[4]
Now select the control and go to the properties pane, look at the TextMode attribute.
clip_image002[4]
Now you can see more options are added here than prior versions of ASP.Net. I just selected Email as TextMode. I added one button to submit my page. The screen shot of the page in Visual Studio 2011 designer is as follows
clip_image003[4]
See the corresponding markup


   

        Enter your email:
           

   

Now let me run this page, IE 9 do not have the support for new form fields. I browsed the page using Firefox and the page appears as below.
clip_image004[4]
From the source of the rendered page, I saw the below markup for my email textbox
Try to enter an invalid email and you will see the browser will ask you to enter a valid one by default.
clip_image005[4]
When rendered in non-supported browsers, these fields are behaving just as normal text boxes. So make sure you are using validation controls with these fields.
See the browser support compatability matrix with these controls with various browser vendors.
clip_image006[4]
ASP.Net 4.5 introduced the support for these new form controls. You can build interactive forms using the newly added controls, keeping in mind that you need to validate the data for non-supported browsers.

Wednesday, November 23, 2011

What is difference between ViewData,ViewBag and TempData in MVC 3.0

ViewData: ViewData is a dictionary of objects that are accessible using strings as keys Eg.
1.ViewData[“JustLearn”]=”Just Learn on Beyond relational is rock!!”
ViewBag:ViewBag uses the dynamic feature that was added in to C# 4.0 It allows an object to dynamically have properties added to it. We can say viewBag=ViewData + dynamic wrapper around the ViewData dictionary. Eg.
1.ViewBag.JustLearn =”Just Learn on beyondrelational is rock!!”
TempData: Temp data use during the current and subsequent request only means it is use when you are sure that next request will be redirecting to next view. Eg.
view source
print?
1.TempData[“JustLearn”]=”Just Learn on beyondrelational is rock!!”
Hold Up

Creating Custom HTML Helpers in ASP.NET MVC

List of built-in HTML Helpers provided by ASP.NET MVC.

ActionLink() – Links to an action method.
BeginForm() – Marks the start of a form and links to the action method that renders the form.
CheckBox() – Renders a check box.
DropDownList() – Renders a drop-down list.
Hidden() – Embeds information in the form that is not rendered for the user to see.
ListBox() – Renders a list box.
Password() – Renders a text box for entering a password.
RadioButton() – Renders a radio button.TextArea() – Renders a text area (multi-line text box).
TextBox () – Renders a text box.

How to develop our own Custom HTML Helpers?

For developing custom HTML helpers the simplest way is to write an extension method for the HtmlHelper class. See the below code, it builds a custom Image HTML Helper for generating image tag.

using System;
using System.Web.Mvc;
namespace MvcHelpers
{
public static class CustomHtmlHelpers
{
public static TagBuilder Image(this HtmlHelper helper, string imageUrl, string alt)
{
if (!String.IsNullOrEmpty(imageUrl))
{
TagBuilder imageTag = new TagBuilder("img");
imageTag.MergeAttribute("src", imageUrl);
imageTag.MergeAttribute("alt", alt);
return imageTag;
}
return null;
}
}
}

TagBuilder represents a class that is used by HTML helpers to build HTML elements.
TagBuilder.MergeAttribute(String, String) method adds an attribute to the tag by using the specified key/value pair.

The next step is in order to make it available to Views, we should include the name space of out custom HTML helper class into Web.config

Build the solution to make sure the helper method is available to views. Goto any view in the solution access the newly created HTML image helper method.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>


Home




<%= Html.Encode(ViewData["Message"]) %>


<%=Html.Image("/Images/logo.png","logo") %>





<%=Html.Image(“/Images/logo.png”,”logo”) %>

The image HTML helper generates the following HTML.

”logo”/

Image Tag Helper is simple example of HTML helpers, we can put any sort of complex logic into HTML Helpers & access them with in the views with a simple method call. in turn which makes the view simpler.

How to return 404 Http status code from ASP.NET MVC Application?

ASP.NET MVC3 includes a new class HttpNotFoundResult in System.Web.Mvc namespace.

HttpNotFoundResult: Instance of HttpNotFoundResult class indicates to client(browser) that the requested resource was not found. It returns a 404 HTTP status code to the client. Generally we return 404 status code if a requested webpage is not available. In case of MVC applications we return 404 status code is in terms of resources, for example we are searching for particular user profile in the portal, if the user profile is not found, we can return 404.

How to return 404 status code from a MVC application?

First way is to instantiate HttpNotFoundResult class and return the object.

public ActionResult Index()
{
var result = new HttpNotFoundResult();
return result;
}

Next alternative is to makes use of HttpNotFound() helper method of the Controller class which returns the HttpNotFoundResult instance.

public ActionResult Index()
{
return HttpNotFound();
}

we can return 404 along with custom status code description,using the overloded version of HttpNotFound(string statusDescription).

public ActionResult Index()
{
return HttpNotFound("can not find requested resource");
}

Friday, November 18, 2011

Why should we use MVC vs normal ASP.NET

There are various positive points to moving towards MVC

1. SEO friendly URL by design (though now this is possible in ASP.NET 4 as well)
2. No ViewState (this may seem a bit of moving backward to some), but overall a good design decision.
3. Clean View Markup (no additional HTML emitted)
4. 100% extensible. You can add your own controller with IOC, switch view engines at will, control model binding at wish etc.
5. Rich UI support (possible through client side JS libraries like jQuery UI and others). Telerik has released some controls for MVC which includes Grid control as well (which are merely HTMLHelpers)
6. Session, JS, Ajax works. Validation is even more powerful with DataAnnotations and jquery.
7. Is MVC faster? Yes by default because of lack of viewstate and clean markup. But performance is subject and MVC by design is more performant that traditional ASP.NET webforms (though webforms can be made as fast as required.
8. Out of the box support for mitigating antiforgery attacks and XSS vulnerability (though asp.net does has this to some extent)
9. Out of the box minimal IOC support.
10. Full control over rendered HTML

MVC 3 dynamic authorization of multiple roles and users

[Authorize(Roles="Admin")]
public ActionResult UpdateArticle(ArticleModel model, int articleid)
{
return View();
}