Search Results

Search found 58374 results on 2335 pages for 'asp net mvc 2 validation'.

Page 12/2335 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Writing Unit Tests for an ASP.NET MVC Action Method that handles Ajax Request and Normal Request

    - by shiju
    In this blog post, I will demonstrate how to write unit tests for an ASP.NET MVC action method, which handles both Ajax request and normal HTTP Request. I will write a unit test for specifying the behavior of an Ajax request and will write another unit test for specifying the behavior of a normal HTTP request. Both Ajax request and normal request will be handled by a single action method. So the ASP.NET MVC action method will be execute HTTP Request object’s IsAjaxRequest method for identifying whether it is an Ajax request or not. So we have to create mock object for Request object and also have to make as a Ajax request from the unit test for verifying the behavior of an Ajax request. I have used NUnit and Moq for writing unit tests. Let me write a unit test for a Ajax request Code Snippet [Test] public void Index_AjaxRequest_Returns_Partial_With_Expense_List() {     // Arrange       Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();     Mock<HttpResponseBase> response = new Mock<HttpResponseBase>();     Mock<HttpContextBase> context = new Mock<HttpContextBase>();       context.Setup(c => c.Request).Returns(request.Object);     context.Setup(c => c.Response).Returns(response.Object);     //Add XMLHttpRequest request header     request.Setup(req => req["X-Requested-With"]).         Returns("XMLHttpRequest");       IEnumerable<Expense> fakeExpenses = GetMockExpenses();     expenseRepository.Setup(x => x.GetMany(It.         IsAny<Expression<Func<Expense, bool>>>())).         Returns(fakeExpenses);     ExpenseController controller = new ExpenseController(         commandBus.Object, categoryRepository.Object,         expenseRepository.Object);     controller.ControllerContext = new ControllerContext(         context.Object, new RouteData(), controller);     // Act     var result = controller.Index(null, null) as PartialViewResult;     // Assert     Assert.AreEqual("_ExpenseList", result.ViewName);     Assert.IsNotNull(result, "View Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<Expense>),             result.ViewData.Model, "Wrong View Model");     var expenses = result.ViewData.Model as IEnumerable<Expense>;     Assert.AreEqual(3, expenses.Count(),         "Got wrong number of Categories");         }   In the above unit test, we are calling Index action method of a controller named ExpenseController, which will returns a PartialView named _ExpenseList, if it is an Ajax request. We have created mock object for HTTPContextBase and setup XMLHttpRequest request header for Request object’s X-Requested-With for making it as a Ajax request. We have specified the ControllerContext property of the controller with mocked object HTTPContextBase. Code Snippet controller.ControllerContext = new ControllerContext(         context.Object, new RouteData(), controller); Let me write a unit test for a normal HTTP method Code Snippet [Test] public void Index_NormalRequest_Returns_Index_With_Expense_List() {     // Arrange               Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();     Mock<HttpResponseBase> response = new Mock<HttpResponseBase>();     Mock<HttpContextBase> context = new Mock<HttpContextBase>();       context.Setup(c => c.Request).Returns(request.Object);     context.Setup(c => c.Response).Returns(response.Object);       IEnumerable<Expense> fakeExpenses = GetMockExpenses();       expenseRepository.Setup(x => x.GetMany(It.         IsAny<Expression<Func<Expense, bool>>>())).         Returns(fakeExpenses);     ExpenseController controller = new ExpenseController(         commandBus.Object, categoryRepository.Object,         expenseRepository.Object);     controller.ControllerContext = new ControllerContext(         context.Object, new RouteData(), controller);     // Act     var result = controller.Index(null, null) as ViewResult;     // Assert     Assert.AreEqual("Index", result.ViewName);     Assert.IsNotNull(result, "View Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<Expense>),             result.ViewData.Model, "Wrong View Model");     var expenses = result.ViewData.Model         as IEnumerable<Expense>;     Assert.AreEqual(3, expenses.Count(),         "Got wrong number of Categories"); }   In the above unit test, we are not specifying the XMLHttpRequest request header for Request object’s X-Requested-With, so that it will be normal HTTP Request. If this is a normal request, the action method will return a ViewResult with a view template named Index. The below is the implementation of Index action method Code Snippet public ActionResult Index(DateTime? startDate, DateTime? endDate) {     //If date is not passed, take current month's first and last date     DateTime dtNow;     dtNow = DateTime.Today;     if (!startDate.HasValue)     {         startDate = new DateTime(dtNow.Year, dtNow.Month, 1);         endDate = startDate.Value.AddMonths(1).AddDays(-1);     }     //take last date of start date's month, if end date is not passed     if (startDate.HasValue && !endDate.HasValue)     {         endDate = (new DateTime(startDate.Value.Year,             startDate.Value.Month, 1)).AddMonths(1).AddDays(-1);     }     var expenses = expenseRepository.GetMany(         exp => exp.Date >= startDate && exp.Date <= endDate);     //if request is Ajax will return partial view     if (Request.IsAjaxRequest())     {         return PartialView("_ExpenseList", expenses);     }     //set start date and end date to ViewBag dictionary     ViewBag.StartDate = startDate.Value.ToShortDateString();     ViewBag.EndDate = endDate.Value.ToShortDateString();     //if request is not ajax     return View("Index",expenses); }   The index action method will returns a PartialView named _ExpenseList, if it is an Ajax request and will returns a View named Index if it is a normal request. Source Code The source code has been taken from my EFMVC app which can download from here

    Read the article

  • Regarding Microsoft MVC framework and usage [closed]

    - by Thomas
    it will be better if some one tell me that what type of web application should develop using Microsoft MVC framework. i am familiar with web form but not familiar with MS MVC framework. i feel any type of web application can be developed with web form. i search google lot to know the specific reason for using MS MVC framework. i am keen interested to know when i should develop web apps using MS MVC framework and when i should use web form. i will be happy if some one discuss this issue in detail. thanks

    Read the article

  • NoSQL with MongoDB, NoRM and ASP.NET MVC

    - by shiju
     In this post, I will give an introduction to how to work on NoSQL and document database with MongoDB , NoRM and ASP.Net MVC 2. NoSQL and Document Database The NoSQL movement is getting big attention in this year and people are widely talking about document databases and NoSQL along with web application scalability. According to Wikipedia, "NoSQL is a movement promoting a loosely defined class of non-relational data stores that break with a long history of relational databases. These data stores may not require fixed table schemas, usually avoid join operations and typically scale horizontally. Academics and papers typically refer to these databases as structured storage". Document databases are schema free so that you can focus on the problem domain and don't have to worry about updating the schema when your domain is evolving. This enables truly a domain driven development. One key pain point of relational database is the synchronization of database schema with your domain entities when your domain is evolving.There are lots of NoSQL implementations are available and both CouchDB and MongoDB got my attention. While evaluating both CouchDB and MongoDB, I found that CouchDB can’t perform dynamic queries and later I picked MongoDB over CouchDB. There are many .Net drivers available for MongoDB document database. MongoDB MongoDB is an open source, scalable, high-performance, schema-free, document-oriented database written in the C++ programming language. It has been developed since October 2007 by 10gen. MongoDB stores your data as binary JSON (BSON) format . MongoDB has been getting a lot of attention and you can see the some of the list of production deployments from here - http://www.mongodb.org/display/DOCS/Production+Deployments NoRM – C# driver for MongoDB NoRM is a C# driver for MongoDB with LINQ support. NoRM project is available on Github at http://github.com/atheken/NoRM. Demo with ASP.NET MVC I will show a simple demo with MongoDB, NoRM and ASP.NET MVC. To work with MongoDB and  NoRM, do the following steps Download the MongoDB databse For Windows 32 bit, download from http://downloads.mongodb.org/win32/mongodb-win32-i386-1.4.1.zip  and for Windows 64 bit, download  from http://downloads.mongodb.org/win32/mongodb-win32-x86_64-1.4.1.zip . The zip contains the mongod.exe for run the server and mongo.exe for the client Download the NorM driver for MongoDB at http://github.com/atheken/NoRM Create a directory call C:\data\db. This is the default location of MongoDB database. You can override the behavior. Run C:\Mongo\bin\mongod.exe. This will start the MongoDb server Now I am going to demonstrate how to program with MongoDb and NoRM in an ASP.NET MVC application.Let’s write a domain class public class Category {            [MongoIdentifier]public ObjectId Id { get; set; } [Required(ErrorMessage = "Name Required")][StringLength(25, ErrorMessage = "Must be less than 25 characters")]public string Name { get; set;}public string Description { get; set; }}  ObjectId is a NoRM type that represents a MongoDB ObjectId. NoRM will automatically update the Id becasue it is decorated by the MongoIdentifier attribute. The next step is to create a mongosession class. This will do the all interactions to the MongoDB. internal class MongoSession<TEntity> : IDisposable{    private readonly MongoQueryProvider provider;     public MongoSession()    {        this.provider = new MongoQueryProvider("Expense");    }     public IQueryable<TEntity> Queryable    {        get { return new MongoQuery<TEntity>(this.provider); }    }     public MongoQueryProvider Provider    {        get { return this.provider; }    }     public void Add<T>(T item) where T : class, new()    {        this.provider.DB.GetCollection<T>().Insert(item);    }     public void Dispose()    {        this.provider.Server.Dispose();     }    public void Delete<T>(T item) where T : class, new()    {        this.provider.DB.GetCollection<T>().Delete(item);    }     public void Drop<T>()    {        this.provider.DB.DropCollection(typeof(T).Name);    }     public void Save<T>(T item) where T : class,new()    {        this.provider.DB.GetCollection<T>().Save(item);                }  }    The MongoSession constrcutor will create an instance of MongoQueryProvider that supports the LINQ expression and also create a database with name "Expense". If database is exists, it will use existing database, otherwise it will create a new databse with name  "Expense". The Save method can be used for both Insert and Update operations. If the object is new one, it will create a new record and otherwise it will update the document with given ObjectId.  Let’s create ASP.NET MVC controller actions for CRUD operations for the domain class Category public class CategoryController : Controller{ //Index - Get the category listpublic ActionResult Index(){    using (var session = new MongoSession<Category>())    {        var categories = session.Queryable.AsEnumerable<Category>();        return View(categories);    }} //edit a single category[HttpGet]public ActionResult Edit(ObjectId id) {     using (var session = new MongoSession<Category>())    {        var category = session.Queryable              .Where(c => c.Id == id)              .FirstOrDefault();         return View("Save",category);    } }// GET: /Category/Create[HttpGet]public ActionResult Create(){    var category = new Category();    return View("Save", category);}//insert or update a category[HttpPost]public ActionResult Save(Category category){    if (!ModelState.IsValid)    {        return View("Save", category);    }    using (var session = new MongoSession<Category>())    {        session.Save(category);        return RedirectToAction("Index");    } }//Delete category[HttpPost]public ActionResult Delete(ObjectId Id){    using (var session = new MongoSession<Category>())    {        var category = session.Queryable              .Where(c => c.Id == Id)              .FirstOrDefault();        session.Delete(category);        var categories = session.Queryable.AsEnumerable<Category>();        return PartialView("CategoryList", categories);    } }        }  You can easily work on MongoDB with NoRM and can use with ASP.NET MVC applications. I have created a repository on CodePlex at http://mongomvc.codeplex.com and you can download the source code of the ASP.NET MVC application from here

    Read the article

  • Creating .NET 3.0 sub-applications within .NET 1.1 applications in IIS/ASP.Net

    - by Karen
    I am basically trying to do the same thing as this question, create a new application within a folder so it could be accessed as follows. * http://www.domain.com/ < Main App * http://www.domain.com/newapp < New App The problem is that newapp is reading the web.config from the Main App, which is causing errors because it doesn't have all the same dlls etc. For New App, in IIS, the starting point is set at /newapp, so I am not sure why it is reading the web.config from / at all. It is set as it's own application. I am testing this in IIS6 on XP Pro, so not sure if that makes a difference. The Main App is dotnet 1.1, and New App is 3.0. Edit: Adding 'inheritInChildApplications to <location doesn't work in 1.1, you get an error: Parser Error Message: Unrecognized attribute 'inheritInChildApplications'

    Read the article

  • Spring MVC: Where to place validation and how to validation entity references.

    - by arrages
    Let's say I have the following command bean for creating a user: public class CreateUserCommand { private String userName; private String email; private Integer occupationId; pirvate Integer countryId; } occupationId and countryId are drop down selected values on the form. They map to an entity in the database (Occupation, Country). This command object is going to be fed to a service facade like so: userServiceFacade.createUser(CreateUserCommand command); This facade will construct a user entity to be sent to the actual service. So I suppose that in the facade layer I will have to make several dao calls to map all the lookup properties of the User entity. Based on this what is the best strategy to validate that occupationId and countryId map to real entities? Where is the best place to perform this validation? There is the spring validator but I am not sure this is the best place for this, for one I am wary of this method as validation is tied to the web tier, but also that means I would need to make the dao calls in the validator for validation but I would need to call the dao's in the facade layer again when the command - entity translation occurs. Is there anything I can do better? Thanks.

    Read the article

  • NoSQL with RavenDB and ASP.NET MVC - Part 1

    - by shiju
     A while back, I have blogged NoSQL with MongoDB, NoRM and ASP.NET MVC Part 1 and Part 2 on how to use MongoDB with an ASP.NET MVC application. The NoSQL movement is getting big attention and RavenDB is the latest addition to the NoSQL and document database world. RavenDB is an Open Source (with a commercial option) document database for the .NET/Windows platform developed  by Ayende Rahien.  Raven stores schema-less JSON documents, allow you to define indexes using Linq queries and focus on low latency and high performance. RavenDB is .NET focused document database which comes with a fully functional .NET client API  and supports LINQ. RavenDB comes with two components, a server and a client API. RavenDB is a REST based system, so you can write your own HTTP cleint API. As a .NET developer, RavenDB is becoming my favorite document database. Unlike other document databases, RavenDB is supports transactions using System.Transactions. Also it's supports both embedded and server mode of database. You can access RavenDB site at http://ravendb.netA demo App with ASP.NET MVCLet's create a simple demo app with RavenDB and ASP.NET MVC. To work with RavenDB, do the following steps. Go to http://ravendb.net/download and download the latest build.Unzip the downloaded file.Go to the /Server directory and run the RavenDB.exe. This will start the RavenDB server listening on localhost:8080You can change the port of RavenDB  by modifying the "Raven/Port" appSetting value in the RavenDB.exe.config file.When running the RavenDB, it will automatically create a database in the /Data directory. You can change the directory name data by modifying "Raven/DataDirt" appSetting value in the RavenDB.exe.config file.RavenDB provides a browser based admin tool. When the Raven server is running, You can be access the browser based admin tool and view and edit documents and index using your browser admin tool. The web admin tool available at http://localhost:8080The below is the some screen shots of web admin tool     Working with ASP.NET MVC  To working with RavenDB in our demo ASP.NET MVC application, do the following steps Step 1 - Add reference to Raven Cleint API In our ASP.NET MVC application, Add a reference to the Raven.Client.Lightweight.dll from the Client directory. Step 2 - Create DocumentStoreThe document store would be created once per application. Let's create a DocumentStore on application start-up in the Global.asax.cs. documentStore = new DocumentStore { Url = "http://localhost:8080/" }; documentStore.Initialise(); The above code will create a Raven DB document store and will be listening the server locahost at port 8080    Step 3 - Create DocumentSession on BeginRequest   Let's create a DocumentSession on BeginRequest event in the Global.asax.cs. We are using the document session for every unit of work. In our demo app, every HTTP request would be a single Unit of Work (UoW). BeginRequest += (sender, args) =>   HttpContext.Current.Items[RavenSessionKey] = documentStore.OpenSession(); Step 4 - Destroy the DocumentSession on EndRequest  EndRequest += (o, eventArgs) => {     var disposable = HttpContext.Current.Items[RavenSessionKey] as IDisposable;     if (disposable != null)         disposable.Dispose(); };  At the end of HTTP request, we are destroying the DocumentSession  object.The below  code block shown all the code in the Global.asax.cs  private const string RavenSessionKey = "RavenMVC.Session"; private static DocumentStore documentStore;   protected void Application_Start() { //Create a DocumentStore in Application_Start //DocumentStore should be created once per application and stored as a singleton. documentStore = new DocumentStore { Url = "http://localhost:8080/" }; documentStore.Initialise(); AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); //DI using Unity 2.0 ConfigureUnity(); }   public MvcApplication() { //Create a DocumentSession on BeginRequest   //create a document session for every unit of work BeginRequest += (sender, args) =>     HttpContext.Current.Items[RavenSessionKey] = documentStore.OpenSession(); //Destroy the DocumentSession on EndRequest EndRequest += (o, eventArgs) => { var disposable = HttpContext.Current.Items[RavenSessionKey] as IDisposable; if (disposable != null) disposable.Dispose(); }; }   //Getting the current DocumentSession public static IDocumentSession CurrentSession {   get { return (IDocumentSession)HttpContext.Current.Items[RavenSessionKey]; } }  We have setup all necessary code in the Global.asax.cs for working with RavenDB. For our demo app, Let’s write a domain class  public class Category {       public string Id { get; set; }       [Required(ErrorMessage = "Name Required")]     [StringLength(25, ErrorMessage = "Must be less than 25 characters")]     public string Name { get; set;}     public string Description { get; set; }   } We have created simple domain entity Category. Let's create repository class for performing CRUD operations against our domain entity Category.  public interface ICategoryRepository {     Category Load(string id);     IEnumerable<Category> GetCategories();     void Save(Category category);     void Delete(string id);       }    public class CategoryRepository : ICategoryRepository {     private IDocumentSession session;     public CategoryRepository()     {             session = MvcApplication.CurrentSession;     }     //Load category based on Id     public Category Load(string id)     {         return session.Load<Category>(id);     }     //Get all categories     public IEnumerable<Category> GetCategories()     {         var categories= session.LuceneQuery<Category>()                 .WaitForNonStaleResults()             .ToArray();         return categories;       }     //Insert/Update category     public void Save(Category category)     {         if (string.IsNullOrEmpty(category.Id))         {             //insert new record             session.Store(category);         }         else         {             //edit record             var categoryToEdit = Load(category.Id);             categoryToEdit.Name = category.Name;             categoryToEdit.Description = category.Description;         }         //save the document session         session.SaveChanges();     }     //delete a category     public void Delete(string id)     {         var category = Load(id);         session.Delete<Category>(category);         session.SaveChanges();     }        } For every CRUD operations, we are taking the current document session object from HttpContext object. session = MvcApplication.CurrentSession; We are calling the static method CurrentSession from the Global.asax.cs public static IDocumentSession CurrentSession {     get { return (IDocumentSession)HttpContext.Current.Items[RavenSessionKey]; } }  Retrieve Entities  The Load method get the single Category object based on the Id. RavenDB is working based on the REST principles and the Id would be like categories/1. The Id would be created by automatically when a new object is inserted to the document store. The REST uri categories/1 represents a single category object with Id representation of 1.   public Category Load(string id) {    return session.Load<Category>(id); } The GetCategories method returns all the categories calling the session.LuceneQuery method. RavenDB is using a lucen query syntax for querying. I will explain more details about querying and indexing in my future posts.   public IEnumerable<Category> GetCategories() {     var categories= session.LuceneQuery<Category>()             .WaitForNonStaleResults()         .ToArray();     return categories;   } Insert/Update entityFor insert/Update a Category entity, we have created Save method in repository class. If  the Id property of Category is null, we call Store method of Documentsession for insert a new record. For editing a existing record, we load the Category object and assign the values to the loaded Category object. The session.SaveChanges() will save the changes to document store.  //Insert/Update category public void Save(Category category) {     if (string.IsNullOrEmpty(category.Id))     {         //insert new record         session.Store(category);     }     else     {         //edit record         var categoryToEdit = Load(category.Id);         categoryToEdit.Name = category.Name;         categoryToEdit.Description = category.Description;     }     //save the document session     session.SaveChanges(); }  Delete Entity  In the Delete method, we call the document session's delete method and call the SaveChanges method to reflect changes in the document store.  public void Delete(string id) {     var category = Load(id);     session.Delete<Category>(category);     session.SaveChanges(); }  Let’s create ASP.NET MVC controller and controller actions for handling CRUD operations for the domain class Category  public class CategoryController : Controller { private ICategoryRepository categoyRepository; //DI enabled constructor public CategoryController(ICategoryRepository categoyRepository) {     this.categoyRepository = categoyRepository; } public ActionResult Index() {         var categories = categoyRepository.GetCategories();     if (categories == null)         return RedirectToAction("Create");     return View(categories); }   [HttpGet] public ActionResult Edit(string id) {     var category = categoyRepository.Load(id);         return View("Save",category); } // GET: /Category/Create [HttpGet] public ActionResult Create() {     var category = new Category();     return View("Save", category); } [HttpPost] public ActionResult Save(Category category) {     if (!ModelState.IsValid)     {         return View("Save", category);     }           categoyRepository.Save(category);         return RedirectToAction("Index");     }        [HttpPost] public ActionResult Delete(string id) {     categoyRepository.Delete(id);     var categories = categoyRepository.GetCategories();     return PartialView("CategoryList", categories);      }        }  RavenDB is an awesome document database and I hope that it will be the winner in .NET space of document database world.  The source code of demo application available at http://ravenmvc.codeplex.com/

    Read the article

  • ASP.NET MVC Case Studies

    - by shiju
     The below are the some of the case studies of ASP.NET MVC Jwaala - Online Banking Solution Benefits after ASP.NET MVC Replaces Ruby on Rails, Linux http://www.microsoft.com/casestudies/Case_Study_Detail.aspx?casestudyid=4000006675 Stack Overflow - Developers See Faster Web Coding, Better Performance with Model-View-Controller http://www.microsoft.com/casestudies/Case_Study_Detail.aspx?casestudyid=4000006676 Kelley Blue Book - Pioneer Provider of Vehicle-Pricing Information Uses Technology to Expand Reach http://www.microsoft.com/casestudies/Case_Study_Detail.aspx?casestudyid=4000006272 

    Read the article

  • ASP.NET MVC 4: Short syntax for script and style bundling

    - by DigiMortal
    ASP.NET MVC 4 introduces new methods for style and scripts bundling. I found something brilliant there I want to introduce you. In this posting I will show you how easy it is to include whole folder with stylesheets or JavaScripts to your page. I’m using ASP.NET MVC 4 Internet Site template for this example. When we open layout pages located in shared views folder we can see something like this in layout file header: <link href="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content/css")" rel="stylesheet" type="text/css" />    <link href="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content/themes/base/css")" rel="stylesheet" type="text/css" />    <script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/js")"></script> Let’s take the last line and modify it so it looks like this: <script src="/Scripts/js"></script> After saving the layout page let’s run browser and see what is coming in over network. As you can see the request to folder ended up with result code 200 which means that request was successful. 327.2KB was received and it is not mark-up size for error page or directory index. Here is the body of response: I scrolled down to point where one script ends and another one starts when I made the screenshot above. All scripts delivered with ASP.NET MVC project templates start with this green note. So now we can be sure that the request to scripts folder ended up with bundled script and not with something else. Conclusion Script and styles bundling uses currently by default long syntax where bundling is done through Bundling class. We can still avoid those long lines and use extremely short syntax for script and styles bundling – we just write usual script or link tag and give folder URL as source. ASP.NET MVC 4 is smart enough to combine styles or scripts when request like this comes in.

    Read the article

  • Model validation with enumerable properties in Asp.net MVC2 RTM

    - by Robert Koritnik
    I'm using DataAnnotations attributes to validate my model objects. My model class looks similar to this: public class MyModel { [Required] public string Title { get; set; } [Required] public List<User> Editors { get; set; } } public class User { public int Id { get; set; } [Required] public string FullName { get; set; } [Required] [DataType(DataType.Email)] public string Email { get; set; } } My controller action looks like: public ActionResult NewItem(MyModel data) { //... } User is presented with a view that has a form with: a text box with dummy name where users enter user's names. For each user they enter, there's a client script coupled with ajax that creates an <input type="hidden" name="data.Editors[0].Id" value="userId" /> for each user entered (enumeration index is therefore not always 0 as written here), so default model binder is able to consume and bind the form without any problems. a text box where users enter the title Since I'm using Asp.net MVC 2 RTM which does model validation instead of input validation I don't know how to avoid validation errors. The thing is I have to use BindAttribute on my controller action. I would have to either provide a white or a black list of properties. It's always a better practice to provide a white list. It's also more future proof. The problem My form works fine, but I get validation errors about user's FullName and Email properties since they are not provided. I also shouldn't feed them to the client (via ajax when user enters user data), because email is personal contact data and is not shared between users. If there was just a single user reference on MyModel I would write [Bind(Include = "Title, Editor.Id")] But I have an enumeration of them. How do I provide Bind white list to work with my model?

    Read the article

  • Mvc2 validation summary and required metadata

    - by Arnis L.
    source code... Thing is, if i specify required metadata using fluent modelmetadata provider like this= public class Foo { public string Bar { get; set; } } public class FooModelMetadataConfiguration : ModelMetadataConfiguration<Foo> { public FooModelMetadataConfiguration() { Configure(x => x.Bar) .Required("lapsa") ; } } And write this into my view = <% Html.BeginForm(); %> <%= Html.ValidationSummary() %> <%= Html.TextBoxFor(x=>x.Bar) %> <% Html.EndForm(); %> And add this to home controller = [HttpPost] public ActionResult Index(Foo foo) { ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View(foo); } It will output this html = <div class="validation-summary-errors"> <ul> <li>lapsa</li> <li>The Bar field is required.</li> </ul> </div> I can't understand why 2nd error is rendered and how to omit it. Author of System.Web.Mvc.Extensibility framework replied with = I think this is a known issue of asp.net mvc, i could not remember the exact location where I have read it, I suggest you post the issue in asp.net mvc issue tracker over codeplex. But before i post anything on issue tracker - i would like to understand first what exactly is wrong. Any help with that?

    Read the article

  • Preventing duplicate Data with ASP.NET AJAX

    - by Yousef_Jadallah
      Some times you need to prevent  User names ,E-mail ID's or other values from being duplicated by a new user during Registration or any other cases,So I will add a simple approach to make the page more user-friendly. Instead the user filled all the Registration fields then press submit after that received a message as a result of PostBack that "THIS USERNAME IS EXIST", Ajax tidies this up by allowing asynchronous querying while the user is still completing the registration form.   ASP.NET enables you to create Web services can be accessed from client script in Web pages by using AJAX technology to make Web service calls. Data is exchanged asynchronously between client and server, typically in JSON format. I’ve added an article to show you step by step  how to use ASP.NET AJAX with Web Services , you can find it here .   Lets go a head with the steps :   1-Create a new project , if you are using VS 2005 you have to create ASP.NET Ajax Enabled Web site.   2-Create your own Database which contain user table that have User_Name field. for Testing I’ve added SQL Server Database that come with Dot Net 2008: Then I’ve created tblUsers:   This table and this structure just for our example, you can use your own table to implement this approach.   3-Add new Item to your project or website, Choose Web Service file, lets say  WebService.cs  .In this Web Service file import System.Data.SqlClient Namespace, Then Add your web method that contain string parameter which received the Username parameter from the Script , Finally don’t forget to qualified the Web Service Class with the ScriptServiceAttribute attribute ([System.Web.Script.Services.ScriptService])     using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data.SqlClient;     [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService {     [WebMethod] public int CheckDuplicate(string User_Name) { string strConn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestDB.mdf;Integrated Security=True;User Instance=True"; string strQuery = "SELECT COUNT(*) FROM tblUsers WHERE User_Name = @User_Name"; SqlConnection con = new SqlConnection(strConn); SqlCommand cmd = new SqlCommand(strQuery, con); cmd.Parameters.Add("User_Name", User_Name); con.Open(); int RetVal= (int)cmd.ExecuteScalar(); con.Close(); return RetVal; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   Our Web Method here is CheckDuplicate Which accept User_Name String as a parameter and return number of the rows , if the name will found in the database this method will return 1 else it will return 0. I’ve applied  [WebMethod] Attribute to our method CheckDuplicate, And applied the ScriptService attribute to a Web Service class named WebService.   4-Add this simple Registration form : <fieldset> <table id="TblRegistratoin" cellpadding="0" cellspacing="0"> <tr> <td> User Name </td> <td> <asp:TextBox ID="txtUserName" onblur="CallWebMethod();" runat="server"></asp:TextBox> </td> <td> <asp:Label ID="lblDuplicate" runat="server" ForeColor="Red" Text=""></asp:Label> </td> </tr> <tr> <td colspan="3"> <asp:Button ID="btnRegistration" runat="server" Text="Registration" /> </td> </tr> </table> </fieldset> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   onblur event is added to the Textbox txtUserName, This event Fires when the Textbox loses the input focus, That mean after the user get focus out from the Textbox CallWebMethod function will be fired. CallWebMethod will be implemented in step 6.   5-Add ScriptManager Control to your aspx file then reference the Web service by adding an asp:ServiceReference child element to the ScriptManager control and setting its path attribute to point to the Web service, That generate a JavaScript proxy class for calling the specified Web service from client script.   <asp:ScriptManager runat="server" ID="scriptManager"> <Services> <asp:ServiceReference Path="WebService.asmx" /> </Services> </asp:ScriptManager> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }     6-Define the JavaScript code to call the Web Service :   <script language="javascript" type="text/javascript">   // This function calls the Web service method // passing simple type parameters and the // callback function function CallWebMethod() { var User_Name = document.getElementById('<%=txtUserName.ClientID %>').value; WebService.CheckDuplicate(User_Name, OnSucceeded, OnError); }   // This is the callback function invoked if the Web service // succeeded function OnSucceeded(result) { var rsltElement = document.getElementById("lblDuplicate"); if (result == 1) rsltElement.innerHTML = "This User Name is exist"; else rsltElement.innerHTML = "";   }   function OnError(error) { // Display the error. alert("Service Error: " + error.get_message()); } </script> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   This call references the WebService Class and CheckDuplicate Web Method defined in the service. It passes a User_Name value obtained from a textbox as well as a callback function named OnSucceeded that should be invoked when the asynchronous Web Service call returns. If the Web Service in different Namespace you can refer it before the class name this Main formula may help you :  NameSpaceName.ClassName.WebMethdName(Parameters , Success callback function, Error callback function); Parameters: you can pass one or many parameters. Success callback function :handles returned data from the service . Error callback function :Any errors that occur when the Web Service is called will trigger in this function. Using Error Callback function is optional.   Hope these steps help you to understand this approach.

    Read the article

  • Preventing duplicate Data with ASP.NET AJAX

    - by Yousef_Jadallah
      Some times you need to prevent  User names ,E-mail ID's or other values from being duplicated by a new user during Registration or any other cases,So I will add a simple approach to make the page more user-friendly. Instead the user filled all the Registration fields then press submit after that received a message as a result of PostBack that "THIS USERNAME IS EXIST", Ajax tidies this up by allowing asynchronous querying while the user is still completing the registration form.   ASP.NET enables you to create Web services can be accessed from client script in Web pages by using AJAX technology to make Web service calls. Data is exchanged asynchronously between client and server, typically in JSON format. I’ve added an article to show you step by step  how to use ASP.NET AJAX with Web Services , you can find it here .   Lets go a head with the steps :   1-Create a new project , if you are using VS 2005 you have to create ASP.NET Ajax Enabled Web site.   2-Create your own Database which contain user table that have User_Name field. for Testing I’ve added SQL Server Database that come with Dot Net 2008: Then I’ve created tblUsers:   This table and this structure just for our example, you can use your own table to implement this approach.   3-Add new Item to your project or website, Choose Web Service file, lets say  WebService.cs  .In this Web Service file import System.Data.SqlClient Namespace, Then Add your web method that contain string parameter which received the Username parameter from the Script , Finally don’t forget to qualified the Web Service Class with the ScriptServiceAttribute attribute ([System.Web.Script.Services.ScriptService])     using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data.SqlClient;     [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService {     [WebMethod] public int CheckDuplicate(string User_Name) { string strConn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestDB.mdf;Integrated Security=True;User Instance=True"; string strQuery = "SELECT COUNT(*) FROM tblUsers WHERE User_Name = @User_Name"; SqlConnection con = new SqlConnection(strConn); SqlCommand cmd = new SqlCommand(strQuery, con); cmd.Parameters.Add("User_Name", User_Name); con.Open(); int RetVal= (int)cmd.ExecuteScalar(); con.Close(); return RetVal; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   Our Web Method here is CheckDuplicate Which accept User_Name String as a parameter and return number of the rows , if the name will found in the database this method will return 1 else it will return 0. I’ve applied  [WebMethod] Attribute to our method CheckDuplicate, And applied the ScriptService attribute to a Web Service class named WebService.   4-Add this simple Registration form : <fieldset> <table id="TblRegistratoin" cellpadding="0" cellspacing="0"> <tr> <td> User Name </td> <td> <asp:TextBox ID="txtUserName" onblur="CallWebMethod();" runat="server"></asp:TextBox> </td> <td> <asp:Label ID="lblDuplicate" runat="server" ForeColor="Red" Text=""></asp:Label> </td> </tr> <tr> <td colspan="3"> <asp:Button ID="btnRegistration" runat="server" Text="Registration" /> </td> </tr> </table> </fieldset> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   onblur event is added to the Textbox txtUserName, This event Fires when the Textbox loses the input focus, That mean after the user get focus out from the Textbox CallWebMethod function will be fired. CallWebMethod will be implemented in step 6.   5-Add ScriptManager Control to your aspx file then reference the Web service by adding an asp:ServiceReference child element to the ScriptManager control and setting its path attribute to point to the Web service, That generate a JavaScript proxy class for calling the specified Web service from client script.   <asp:ScriptManager runat="server" ID="scriptManager"> <Services> <asp:ServiceReference Path="WebService.asmx" /> </Services> </asp:ScriptManager> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }     6-Define the JavaScript code to call the Web Service :   <script language="javascript" type="text/javascript">   // This function calls the Web service method // passing simple type parameters and the // callback function function CallWebMethod() { var User_Name = document.getElementById('<%=txtUserName.ClientID %>').value; WebService.CheckDuplicate(User_Name, OnSucceeded, OnError); }   // This is the callback function invoked if the Web service // succeeded function OnSucceeded(result) { var rsltElement = document.getElementById("lblDuplicate"); if (result == 1) rsltElement.innerHTML = "This User Name is exist"; else rsltElement.innerHTML = "";   }   function OnError(error) { // Display the error. alert("Service Error: " + error.get_message()); } </script> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   This call references the WebService Class and CheckDuplicate Web Method defined in the service. It passes a User_Name value obtained from a textbox as well as a callback function named OnSucceeded that should be invoked when the asynchronous Web Service call returns. If the Web Service in different Namespace you can refer it before the class name this Main formula may help you :  NameSpaceName.ClassName.WebMethdName(Parameters , Success callback function, Error callback function); Parameters: you can pass one or many parameters. Success callback function :handles returned data from the service . Error callback function :Any errors that occur when the Web Service is called will trigger in this function. Using Error Callback function is optional.   Hope these steps help you to understand this approach.

    Read the article

  • .Net to Oracle Connectivity using ODBC .NET

    - by SAMIR BHOGAYTA
    You can use the new ODBC .NET Data Provider that works with the ODBC Oracle7.x driver or higher. You need to have MDAC 2.6 or later installed and then download ODBC .NET from the MS Web Site http://msdn.microsoft.com/downloads/default.asp?url=/code/sample.asp?url=/msdn-files/027/001/668/msdncompositedoc.xml&frame=true. MDAC (Microsoft Data Access Component) 2.7 contains core component, including the Microsoft SQL server and Oracle OLE Database provider and ODBC driver. Insta ...You can use the new ODBC .NET Data Provider that works with the ODBC Oracle7.x driver or higher. You need to have MDAC 2.6 or later installed and then download ODBC .NET from the MS Web Site http://msdn.microsoft.com/downloads/default.asp?url=/code/sample.asp?url=/msdn-files/027/001/668/msdncompositedoc.xml&frame=true. MDAC (Microsoft Data Access Component) 2.7 contains core component, including the Microsoft SQL server and Oracle OLE Database provider and ODBC driver. Install ODBC .NET from the MS Web Site http://msdn.microsoft.com/downloads/default.asp?URL=/downloads/sample.asp?url=/msdn-files/027/001/943/msdncompositedoc.xml Create a DSN, using either Microsoft ODBC for Oracle or Oracle supplied Driver if the Oracle client software is loaded. here for eq. TrailDSN. While creating DSN give user name along with passward for eq. scott/tiger. using Microsoft .Data.Odbc; private void Form1_Load(object sender, System.EventArgs e) { try { OdbcConnection myconnection= new OdbcConnection ("DSN=TrialDSN"); OdbcDataAdapter myda = new OdbcDataAdapter ("Select * from EMP", myconnection); DataSet ds= new DataSet (); myda.Fill(ds, "Table"); dataGrid1.DataSource = ds ; } catch(Exception ex) { MessageBox.Show (ex.Message ); } }

    Read the article

  • Using .net 3.5 assemblies in asp.net 2.0 web application

    - by masterik
    I have an .net assembly build against 3.5 framework. This assembly has a class Foo with two method overrides: public class Foo { public T Set<T>(T value); public T Set<T>(Func<T> getValueFunc); } I'm referencing this assembly in my asp.net 2.0 web application to use first override of the Set method (without Func). But on build I get an error saying that I should reference System.Core to use System.Func delegate... but I'm not using this type... Is there a workaround to solve this? PS: There is no option to convert my web application targeting 3.5 framework.

    Read the article

  • DataAnnotations jQuery validation in asp.net mvc 2

    - by Anonimous
    Hi, I trying to use jQuery validation plugin with DataAnnotations in asp.net mvc 2 final. Now I'm using MicrosoftMvcValidation.js and it works. But I can't find way to work with jQuery validation. I read about MicrosoftMvcJQueryValidation.js. But I think that it is obsolete. How can I use DataAnnotations with jQuery validation plugin?

    Read the article

  • Is server validation necessary with client-side validators?

    - by peroija
    I recently created a .net web app that used over 200 custom validators on one page. I wrote code for both ClientValidationFunction and OnServerValidate which results in a ton of repetitive code. My sql statements are parameterized, I have functions that pull data from input fields and validates them before passing to the sql statements or stored procedures. And the javascript validates the fields before the page submits. So essentially the data is clean and valid before it even hits the OnServerValidate and clean after it anyways due to the aforementioned steps. This makes me question, is OnServerValidate really needed when I validate on the clientside?

    Read the article

  • ASP.NET MVC: How do I validate a model wrapped in a ViewModel?

    - by Deniz Dogan
    For the login page of my website I would like to list the latest news for my site and also display a few fields to let the user log in. So I figured I should make a login view model - I call this LoginVM. LoginVM contains a Login model for the login fields and a List<NewsItem> for the news listing. This is the Login model: public class Login { [Required(ErrorMessage="Enter a username.")] [DisplayName("Username")] public string Username { get; set; } [Required(ErrorMessage="Enter a password.")] [DataType(DataType.Password)] [DisplayName("Password")] public string Password { get; set; } } This is the LoginVM view model: public class LoginVM { public Login login { get; set; } public List<NewsItem> newsItems { get; set; } } This is where I get stuck. In my login controller, I get passed a LoginVM. [HttpPost] public ActionResult Login(LoginVM model, FormCollection form) { if (ModelState.IsValid) { // What? In the code I'm checking whether ModelState is valid and this would work fine if the view model was actually the Login model, but now it's LoginVM which has no validation attributes at all. How do I make LoginVM "traverse" through its members to validate them all? Am I doing something fundamentally wrong using ModelState in this manner?

    Read the article

  • ASP.NET Web API - Screencast series with downloadable sample code - Part 1

    - by Jon Galloway
    There's a lot of great ASP.NET Web API content on the ASP.NET website at http://asp.net/web-api. I mentioned my screencast series in original announcement post, but we've since added the sample code so I thought it was worth pointing the series out specifically. This is an introductory screencast series that walks through from File / New Project to some more advanced scenarios like Custom Validation and Authorization. The screencast videos are all short (3-5 minutes) and the sample code for the series is both available for download and browsable online. I did the screencasts, but the samples were written by the ASP.NET Web API team. So - let's watch them together! Grab some popcorn and pay attention, because these are short. After each video, I'll talk about what I thought was important. I'm embedding the videos using HTML5 (MP4) with Silverlight fallback, but if something goes wrong or your browser / device / whatever doesn't support them, I'll include the link to where the videos are more professionally hosted on the ASP.NET site. Note also if you're following along with the samples that, since Part 1 just looks at the File / New Project step, the screencast part numbers are one ahead of the sample part numbers - so screencast 4 matches with sample code demo 3. Note: I started this as one long post for all 6 parts, but as it grew over 2000 words I figured it'd be better to break it up. Part 1: Your First Web API [Video and code on the ASP.NET site] This screencast starts with an overview of why you'd want to use ASP.NET Web API: Reach more clients (thinking beyond the browser to mobile clients, other applications, etc.) Scale (who doesn't love the cloud?!) Embrace HTTP (a focus on HTTP both on client and server really simplifies and focuses service interactions) Next, I start a new ASP.NET Web API application and show some of the basics of the ApiController. We don't write any new code in this first step, just look at the example controller that's created by File / New Project. using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web.Http; namespace NewProject_Mvc4BetaWebApi.Controllers { public class ValuesController : ApiController { // GET /api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET /api/values/5 public string Get(int id) { return "value"; } // POST /api/values public void Post(string value) { } // PUT /api/values/5 public void Put(int id, string value) { } // DELETE /api/values/5 public void Delete(int id) { } } } Finally, we walk through testing the output of this API controller using browser tools. There are several ways you can test API output, including Fiddler (as described by Scott Hanselman in this post) and built-in developer tools available in all modern browsers. For simplicity I used Internet Explorer 9 F12 developer tools, but you're of course welcome to use whatever you'd like. A few important things to note: This class derives from an ApiController base class, not the standard ASP.NET MVC Controller base class. They're similar in places where API's and HTML returning controller uses are similar, and different where API and HTML use differ. A good example of where those things are different is in the routing conventions. In an HTTP controller, there's no need for an "action" to be specified, since the HTTP verbs are the actions. We don't need to do anything to map verbs to actions; when a request comes in to /api/values/5 with the DELETE HTTP verb, it'll automatically be handled by the Delete method in an ApiController. The comments above the API methods show sample URL's and HTTP verbs, so we can test out the first two GET methods by browsing to the site in IE9, hitting F12 to bring up the tools, and entering /api/values in the URL: That sample action returns a list of values. To get just one value back, we'd browse to /values/5: That's it for Part 1. In Part 2 we'll look at getting data (beyond hardcoded strings) and start building out a sample application.

    Read the article

  • Dyanamic client side validation

    - by Noel
    Is anyone doing dyanamic client validation and if so how are you doing it. I have a view where client side validation is enabled through jquery validator ( see below) <script src="../../Scripts/jquery-1.3.2.js" type="text/javascript"></script> <script src="../../Scripts/jquery.validate.js" type="text/javascript"></script> <script src="../../Scripts/MicrosoftMvcJQueryValidation.js" type="text/javascript"></script> <% Html.EnableClientValidation(); %> This results in javascript code been generated on my page which calls validate when I click the submit button: function __MVC_EnableClientValidation(validationContext) { .... theForm.validate(options); } If I want validation to occur when the onblur event occurs on a textbox how can i get this to work?

    Read the article

  • Top 5 reasons for using ASP.NET MVC 2 rather than ASP.NET MVC 1

    - by Richard Ev
    I've been using ASP.NET MVC 1 for a while now, and am keen to take advantage of the improvements in MVC 2. Things like validation seem greatly improved, and strongly-typed HTML helper methods look great. So, for those of you who have real-world practical experience of using ASP.NET MVC 1 and are now using MVC 2, what are your top 5 reasons for using MVC 2?

    Read the article

  • Reuse an MVC area in multiple MVC applications?

    - by James Newton-King
    I have some common web pages that will be in multiple MVC applications. For those pages I'd like to reuse the same source code (controllers + views) between the different MVC web sites. What is the best way to go about doing this? ASP.NET MVC areas seem like one possibility but they just a sub directory of the website project. Is it possible to reuse an MVC area in multiple MVC applications?

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >