Search Results

Search found 567 results on 23 pages for 'mvc2'.

Page 6/23 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • ASP.NET MVC2 Radio Button generates duplicate HTML id-s

    - by Dmitriy Nagirnyak
    Hi, It seems that the default ASP.NET MVC2 Html helper generates duplicate HTML IDs when using code like this (EditorTemplates/UserType.ascx): <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<UserType>" %> <%: Html.RadioButton("", UserType.Primary, Model == UserType.Primary) %> <%: Html.RadioButton("", UserType.Standard, Model == UserType.Standard) %> <%: Html.RadioButton("", UserType.ReadOnly, Model == UserType.ReadOnly) %> The HTML it produces is: <input checked="checked" id="UserType" name="UserType" type="radio" value="Primary" /> <input id="UserType" name="UserType" type="radio" value="Standard" /> <input id="UserType" name="UserType" type="radio" value="ReadOnly" /> That clearly shows a problem. So I must be misusing the Helper or something. I can manually specify the id as html attribute but then I cannot guarantee it will be unique. So the question is how to make sure that the IDs generated by RadioButton helper are unique for each value and still preserve the conventions for generating those IDs (so nested models are respected? (Preferably not generating IDs manually.) Thanks, Dmitriy,

    Read the article

  • maxlength attribute of a text box from the DataAnnotations StringLength in MVC2

    - by Pervez Choudhury
    I am working on an MVC2 application and want to set the maxlength attributes of the text inputs. I have already defined the stringlength attribute on the Model object using data annotations and it is validating the length of entered strings correctly. I do not want to repeat the same setting in my views by setting the max length attribute manually when the model already has the information. Is there any way to do this? Code snippets below: From the Model: [Required, StringLength(50)] public string Address1 { get; set; } From the View: <%= Html.LabelFor(model => model.Address1) %> <%= Html.TextBoxFor(model => model.Address1, new { @class = "text long" })%> <%= Html.ValidationMessageFor(model => model.Address1) %> What I want to avoid doing is: <%= Html.TextBoxFor(model => model.Address1, new { @class = "text long", maxlength="50" })%> Is there any way to do this?

    Read the article

  • ASP.Net MVC2 (RTM) breaks response filtering - "Filtering is not allowed"

    - by womp
    I've just done a test run of upgrading a project to ASP.Net MVC 2 (RTM) in anticipation of the full official .Net 4.0 release coming later this month. Our application is using a minimizer for our CSS and javascript. To do so, it is making use of the HttpResponse.Filter property to set a custom filter. With the upgrade, the setter for this property is throwing an HttpException saying "Filtering is not allowed." Looking that the HttpResponse.Filter property in reflector shows this: set { if (!this.UsingHttpWriter) { throw new HttpException(SR.GetString("Filtering_not_allowed")); } ... private bool UsingHttpWriter { get { return ((this._httpWriter != null) && (this._writer == this._httpWriter)); } } Clearly something has changed in the way the HttpResponse is writing to the output stream in MVC2. Does anyone know what the change is, or at least a workaround for this? EDIT: This seems pretty radical. Some further investigation shows that ASP.Net MVC 2 RTM is using a System.Web.Mvc.ViewPage.SwitchWriter as the Output property of an HttpResponse, whereas MVC 1 was using a plain old HttpWriter. That explains why the exception is being thrown. But that doesn't explain why they've chosen to completely break this functionality. This thread seems to indicate that this is just temporary... but this makes me pretty nervous... this is the RTM after all. Any further comments appreciated on this.

    Read the article

  • MVC2: Validate PartialView before Form Submit of Page containing Partial View

    - by Pascal
    I am using asp.net mvc2 and having a basic Page that includes a Partial View within a form <% using (Html.BeginForm()) { %> <% Html.RenderAction("partialViewActionName", "Controllername"); %> <input type="submit" value="Weiter" /> <% } %> When I submit the form, the httpPost Action of my Page is called, and AFTER that the httpPost Action of my Partial View is called [HttpPost] public virtual ActionResult PagePostMethod(myModel model) { // here I should know about the validation of my partial View // If partialView.ModelState is valid then // return View("success"); // else return View(model) } [HttpPost] public virtual ActionResult partialViewActionName(myModel model) { ModelState.AddModelError("Error"); return View(model); } But as I am doing the Validation in the httpPost Method of my Partial View (because I want to use my Partial View in several Places) I cant decide if my hole page is valid or not. Has anyone an Idea how I could do this? Isn´t it a common task to have several partial Views in a page but have the information about validation in the page action methods? Thanks very much for your help!!

    Read the article

  • ASP.NET MVC2 Routing Issue With StructureMap

    - by alphadogg
    So, in global.asax, I have: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute(" { *favicon }", new { favicon = @"(.*/)?favicon.ico(/.*)?" }); routes.IgnoreRoute("{*robotstxt}", new { robotstxt = @"(.*/)?robots.txt(/.*)?" }); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { var container = new Container(); ServiceLocator.SetLocatorProvider(() => new StructureMapServiceLocator(container)); ComponentRegistrar.Register(container); Debug.WriteLine(container.WhatDoIHave()); // original MVC2 code at project startup AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } and in my StructureMapControllerFactory, I have: protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (requestContext == null) { throw new ArgumentNullException("requestContext"); } if (controllerType == null) { //return base.GetControllerInstance(requestContext, controllerType); controllerType = GetControllerType(requestContext, "Home"); requestContext.RouteData.Values["Controller"] = "Home"; requestContext.RouteData.Values["action"] = "Index"; } try { return theContainer.GetInstance(controllerType) as Controller; } catch (StructureMapException) { System.Diagnostics.Debug.WriteLine(theContainer.WhatDoIHave()); throw; } } Now, normally, in most examples you find on the net, when controllerType is null, you have the commented out line (base.GetControllerInstance()) that handles it. However, if I use that, I get an error about not finding the controller for default.aspx when the controllerType is null at startup of the web app. If I force the use of the Home controller, I get the site to appear. What am I doing wrong? Is it a problem in routing?

    Read the article

  • Using FluentValidation with Castle Windsor and Entity Framework 4.0 (POCO) in MVC2

    - by Brian McCord
    This isn't a very simple question, but hopefully someone has run across it. I am trying to get the following things working together: MVC2 FluentValidation Entity Framework 4.0 (POCO) Castle Windsor I've pretty much gotten everything working. I have Castle Windsor implemented and working with the Controllers being served up by the WindsorControllerFactory that is part of MVCContrib. I also have Castle serving up the FluentValidation validators as is described by this article: http://www.jeremyskinner.co.uk/2010/02/22/using-fluentvalidation-with-an-ioc-container/ My problem comes in when I try to use Html.EditorForModel or EditorFor on a view. When I try to do that I get this error message: No component for supporting the service FluentValidation.IValidator`1[[System.Data.Entity.DynamicProxies.State_71C51A42554BA6C3CF05105DA05435AD209602C217FC4C34CA52ACEA2B06B99B, EntityFrameworkDynamicProxies-BrindleyInsurance.BusinessObjects, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] was found This is due to using the POCO generation on Entity Framework 4.0. At runtime, the generated classes get wrapped with a Dynamic Proxy so tracking and lazy loading can happen. Apparently, when using EditorForModel or EditorFor, it tries to ask Windsor to create a validator for the dynamic proxy type instead of the underlying real type. Does anyone know what I can do to solve this issue?

    Read the article

  • C# mvc2 client side form validation with xval, prevent post

    - by Rob
    I'm using xval to use client side validation in my asp.net mvc2 webapplication. Despite the errors it's giving when i enter text in a nummeric field it still tries to post the form to the database. The incorrect values are being replaced by 0 and saved to the database. But instead it shouldn't even be possible to try and submit the form. Can anyone help me out here? I've set the attributes as below; [Property] [ShowColumnInCrud(true, label = "FromPriceInCents")] [Required] //[Range(1, Int32.MaxValue)] public virtual Int32 FromPriceInCents{ get; set; } The controller catching the request looks as below; I'm getting no errors in this part. [AcceptVerbs(HttpVerbs.Post)] [Transaction] [ValidateInput(false)] public override ActionResult Create() { //some foo happens } My view looks like below; <div class="label"><label for="Price">FromPrice</label></div> <div class="field"> <%= Html.TextBox("FromPriceInCents")%> <%= Html.ValidationMessage("product.FromPriceInCents")%></div> And at the end of the view i have the following rule which in html code generates the correct validation rules <%= Html.ClientSideValidation<Product>("Product") %> I hope someone can helps me out with this issue, thanks in advance!

    Read the article

  • Asp.Net MVC2 Clientside Validation problem with controls with prefixes

    - by alexander
    The problem is: when I put 2 controls of the same type on a page I need to specify different prefixes for binding. In this case the validation rules generated right after the form are incorrect. So how to get client validation work for the case?: the page contains: <% Html.RenderPartial(ViewLocations.Shared.PhoneEditPartial, new PhoneViewModel { Phone = person.PhonePhone, Prefix = "PhonePhone" }); Html.RenderPartial(ViewLocations.Shared.PhoneEditPartial, new PhoneViewModel { Phone = person.FaxPhone, Prefix = "FaxPhone" }); %> the control ViewUserControl<PhoneViewModel>: <%= Html.TextBox(Model.GetPrefixed("CountryCode"), Model.Phone.CountryCode) %> <%= Html.ValidationMessage("Phone.CountryCode", new { id = Model.GetPrefixed("CountryCode"), name = Model.GetPrefixed("CountryCode") })%> where Model.GetPrefixed("CountryCode") just returns "FaxPhone.CountryCode" or "PhonePhone.CountryCode" depending on prefix And here is the validation rules generated after the form. They are duplicated for the field name "Phone.CountryCode". While the desired result is 2 rules (required, number) for each of the FieldNames "FaxPhone.CountryCode", "PhonePhone.CountryCode" The question is somewhat duplicate of http://stackoverflow.com/questions/2675606/asp-net-mvc2-clientside-validation-and-duplicate-ids-problem but the advise to manually generate ids doesn't helps.

    Read the article

  • MVC2 and jquery.validate.js

    - by Will I Am
    I am experiencing some confusion with jquery.validate.js First of all, what is MicrosoftMvcJqueryValidation.js. It is referenced in snippets on the web but appears to have dissapeared from the RTM MVC2 and is now in futures. Do I need it? The reason I'm asking is that I'm trying to use the validator with MVC and I can't get it to work. I defined my JS as: $(document).ready(function () { $("#myForm").validate({ rules: { f_fullname: { required: true }, f_email: { required: true, email: true }, f_email_c: { equalTo: "#f_email" }, f_password: { required: true, minlength: 6 }, f_password_c: { equalTo: "#f_password" } }, messages: { f_fullname: { required: "* required" }, f_email: { required: "* required", email: "* not a valid email address" }, f_email_c: { equalTo: "* does not match the other email" }, f_password: { required: "* required", minlength: "password must be at least 6 characters long" }, f_password_c: { equalTo: "* does not match the other email" } } }); }); and my form on the view: <% using (Html.BeginForm("CreateNew", "Account", FormMethod.Post, new { id = "myForm" })) { %> <fieldset> <label for="f_fullname">name:</label><input id="f_fullname"/> <label for="f_email"><input id="f_email"/> ...etc... <input type="submit" value="Create" id="f_submit"/> </fieldset> <% } %> and the validation method gets called on .ready() with no errors in firebug. however when I submit the form, nothing gets validated and the form gets submitted. If I create a submitHandler() it gets called, but the plugin doesn't detect any validation errors (.valid() == true) What am I missing?

    Read the article

  • Converting From Castle Windsor To StructureMap In An MVC2 Project

    - by alphadogg
    I am learning about best practices in MVC2 and I am knocking off a copy of the "Who Can Help Me" project (http://whocanhelpme.codeplex.com/) off Codeplex. In it, they use Castle Windsor for their DI container. One "learning" task I am trying to do is convert this subsystem in this project to use StructureMap. Basically, at Application_Start(), the code news up a Windsor container. Then, it goes through multiple assemblies, using MEF: public static void Register(IContainer container) { var catalog = new CatalogBuilder() .ForAssembly(typeof(IComponentRegistrarMarker).Assembly) .ForMvcAssembly(Assembly.GetExecutingAssembly()) .ForMvcAssembliesInDirectory(HttpRuntime.BinDirectory, "CPOP*.dll") // Won't work in Partial trust .Build(); var compositionContainer = new CompositionContainer(catalog); compositionContainer .GetExports<IComponentRegistrar>() .Each(e => e.Value.Register(container)); } and any class in any assembly that has an IComponentRegistrar interface will get its Register() method run. For example, the controller registrar's Register() method implementation basically is: public void Register(IContainer container) { Assembly.GetAssembly(typeof(ControllersRegistrarMarker)).GetExportedTypes() .Where(IsController) .Each(type => container.AddComponentLifeStyle( type.Name.ToLower(), type, LifestyleType.Transient )); } private static bool IsController(Type type) { return typeof(IController).IsAssignableFrom(type); } Hopefully, I am not butchering WCHM too much. I am wondering how does one do this with StructureMap?

    Read the article

  • MVC2 Client Validation isn't working when getting form from ajax call

    - by devlife
    I'm trying to use MVC2 client-side validation in a partial view that is rendered via $.get. However, the client validation isn't working. I'm not quite sure what the deal is. [Required(ErrorMessage = "Email is required")] public string Email { get; set; } <% using ( Ajax.BeginForm( new AjaxOptions { Confirm = "You sure?" } ) ) { %> <%: Html.TextBoxFor( m => m.Email, new { @class = "TextBox150" } )%> <%= Html.ValidationMessageFor( m => m.Email )%> <input type="submit" value="Add/Save" style="float: right;" /> <% } %> I'm not doing anything special to render the the partial view. Just putting the html into a div and showing it in a modal popup. On a side note, does anyone know if it's possible to submit the form with client validation without a submit button?

    Read the article

  • MVC2 DataAnnotations on ViewModel - Don't understand using it with MVVM pattern

    - by ScottSEA
    I have an MVC2 Application that uses MVVM pattern. I am trying use Data Annotations to validate form input. In my ThingsController I have two methods: [HttpGet] public ActionResult Index() { return View(); } public ActionResult Details(ThingsViewModel tvm) { if (!ModelState.IsValid) return View(tvm); try { Query q = new Query(tvm.Query); ThingRepository repository = new ThingRepository(q); tvm.Things = repository.All(); return View(tvm); } catch (Exception) { return View(); } } My Details.aspx view is strongly typed to the ThingsViewModel: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Config.Web.Models.ThingsViewModel>" %> The ViewModel is a class consisting of a IList of returned Thing objects and the Query string (which is submitted on the form) and has the Required data annotation: public class ThingsViewModel { public IList<Thing> Things{ get; set; } [Required(ErrorMessage="You must enter a query")] public string Query { get; set; } } When I run this, and click the submit button on the form without entering a value I get a YSOD with the following error: The model item passed into the dictionary is of type 'Config.Web.Models.ThingsViewModel', but this dictionary requires a model item of type System.Collections.Generic.IEnumerable`1[Config.Domain.Entities.Thing]'. How can I get Data Annotations to work with a ViewModel? I cannot see what I'm missing or where I'm going wrong - the VM was working just fine before I started mucking around with validation.

    Read the article

  • Does ASP.NET Tracing work in MVC2 Views?

    - by AUSTX_RJL
    I have a VS 2010 MVC2 .NET 4.0 web application. ASP.NET tracing is enabled both in the Page directive (Trace="true) and in the Web.config: <trace enabled="true" requestLimit="10" pageOutput="true" traceMode="SortByTime" localOnly="true" writeToDiagnosticsTrace="true" /> A standard trace listener is also configured in the Web.config: <trace autoflush="true" indentsize="4"> <listeners> <add name="WebPageTrace" type="System.Web.WebPageTraceListener, System.Web, Version=4.0.30319.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> <add name="TextWriterTrace" type="System.Diagnostics.TextWriterTraceListener" initializeData="textListener.log" /> </listeners> </trace> Tracing works fine from the controller, but when I add a Trace in the View (.aspx) nothing ever shows: <% System.Diagnostics.Trace.WriteLine("Message System.Diagnostics.Trace from View"); %> <% Page.Trace.Write("Message Page.Trace from View"); %> Is this supposed to work? Is there something else that is needed to enable Tracing from a View? Thanks

    Read the article

  • Discusses some issues related to mvc2.0

    - by hao123
    ???????????????,???????? ??: ???????:1????????2????????3???? ?????????????? ??????:1???????:http://demo.com/admin/News/index 2???????:http://demo.com/s7mmer/News/index 3?????:http://demo.com/News/index ??asp.net mvc1.0???????????,?????,??asp.net mvc2.0???Areas?? ??: ???????,?????????????Admin?areas,??VS?????????????areas????,????????????????? ??????????: 1?????????Areas???? 2??Areas ???????? 3?????,?Areas?????????MyAreaRegistration.cs ????: ?? using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace S7mmer.Web { public class AdminAreaRegistration : AreaRegistration { public override string AreaName { get { return "Admin"; } } public override void RegisterArea(AreaRegistrationContext context) { //?????????? context.MapRoute( "AdminController_default", "Admin/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" }, // Parameter defaults new string[] { "S7mmer.Web.Areas.Admin.Controllers" }//controllers????? ); } } public class S7mmerAreaRegistration : AreaRegistration { public override string AreaName { get { return "S7mmer"; } } public override void RegisterArea(AreaRegistrationContext context) { //?????????? context.MapRoute( "S7mmerController_default", "S7mmer/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" }, // Parameter defaults new string[] { "S7mmer.Web.Areas.S7mmer.Controllers" }//controllers????? ); } } public class WebSiteAreaRegistration : AreaRegistration { public override string AreaName { get { return "WebSite"; } } public override void RegisterArea(AreaRegistrationContext context) { //?????????? context.MapRoute( "WebSiteController_default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" }, // Parameter defaults new string[] { "S7mmer.Web.Areas.WebSite.Controllers" }//controllers????? ); } } } 4??Areas?????Admin????????NewsController.cs 5??NewsController.cs??public ActionResult Index()?????view,??? ???news????index.aspx 6????????Global.asax??,?Application_Start()????AreaRegistration.RegisterAllAreas(); protected void Application_Start() { AreaRegistration.RegisterAllAreas(); // RegisterRoutes(RouteTable.Routes); } ????? http://localhost:1108/admin/News/index,??????????! ??????????????????,???????????????,????

    Read the article

  • Bug with asp.net mvc2, collection and ValidationMessageFor ?

    - by Rafael Mueller
    I'm with a really weird bug with asp.net mvc2 (rtm) and ValidationMessageFor. The example below throws a System.Collections.Generic.KeyNotFoundException on Response.Write(Html.ValidationMessageFor(n = n[index].Name)); Any ideas why thats happening? I'm accessing the same dictionary twice before, but it only throws the error on ValidationMessageFor, any thoughts? Here's the code. public class Parent { public IList<Child> Childrens { get; set; } [Required] public string Name { get; set; } } public class Child { [Required] public string Name { get; set; } } The controller public class ParentController : Controller { public ActionResult Create() { var parent = new Parent { Name = "Parent" }; parent.Childrens = new List<Child> { new Child(), new Child(), new Child() }; return View(parent); } } The view (Create.aspx) <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Parent>" %> <%@ Import Namespace="BugAspNetMVC" %> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <%Html.EnableClientValidation(); %> <% using (Html.BeginForm()) {%> <%=Html.LabelFor(p => p.Name)%> <%=Html.TextBoxFor(p => p.Name)%> <%=Html.ValidationMessageFor(p => p.Name)%> <%Html.RenderPartial("Childrens", Model.Childrens); %> <%} %> </asp:Content> And the partial view (Childrens.ascx) <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IList<Child>>" %> <%@ Import Namespace="BugAspNetMVC"%> <% for (int i = 0; i < Model.Count; i++) { var index = i; Response.Write(Html.LabelFor(n => n[index].Name)); Response.Write(Html.TextBoxFor(n => n[index].Name)); Response.Write(Html.ValidationMessageFor(n => n[index].Name)); } %>

    Read the article

  • ASP.NET MVC2: Getting textbox data from a view to a controller

    - by mr_plumley
    Hi, I'm having difficulty getting data from a textbox into a Controller. I've read about a few ways to accomplish this in Sanderson's book, Pro ASP.NET MVC Framework, but haven't had any success. Also, I've ran across a few similiar questions online, but haven't had any success there either. Seems like I'm missing something rather fundamental. Currently, I'm trying to use the action method parameters approach. Can someone point out where I'm going wrong or provide a simple example? Thanks in advance! Using Visual Studio 2008, ASP.NET MVC2 and C#: What I would like to do is take the data entered in the "Investigator" textbox and use it to filter investigators in the controller. I plan on doing this in the List method (which is already functional), however, I'm using the SearchResults method for debugging. Here's the textbox code from my view, SearchDetails: <h2>Search Details</h2> <% using (Html.BeginForm()) { %> <fieldset> <%= Html.ValidationSummary() %> <h4>Investigator</h4> <p> <%=Html.TextBox("Investigator")%> <%= Html.ActionLink("Search", "SearchResults")%> </p> </fieldset> <% } %> Here is the code from my controller, InvestigatorsController: private IInvestigatorsRepository investigatorsRepository; public InvestigatorsController(IInvestigatorsRepository investigatorsRepository) { //IoC: this.investigatorsRepository = investigatorsRepository; } public ActionResult List() { return View(investigatorsRepository.Investigators.ToList()); } public ActionResult SearchDetails() { return View(); } public ActionResult SearchResults(SearchCriteria search) { string test = search.Investigator; return View(); } I have an Investigator class: [Table(Name = "INVESTIGATOR")] public class Investigator { [Column(IsPrimaryKey = true, IsDbGenerated = false, AutoSync=AutoSync.OnInsert)] public string INVESTID { get; set; } [Column] public string INVEST_FNAME { get; set; } [Column] public string INVEST_MNAME { get; set; } [Column] public string INVEST_LNAME { get; set; } } and created a SearchCriteria class to see if I could get MVC to push the search criteria data to it and grab it in the controller: public class SearchCriteria { public string Investigator { get; set; } } } I'm not sure if project layout has anything to do with this either, but I'm using the 3 project approach suggested by Sanderson: DomainModel, Tests, and WebUI. The Investigator and SearcCriteria classes are in the DomainModel project and the other items mentioned here are in the WebUI project. Thanks again for any hints, tips, or simple examples! Mike

    Read the article

  • Common DataAnnotations in ASP.Net MVC2

    - by Scott Mayfield
    Howdy, I have what should be a simple question. I have a set of validations that use System.CompontentModel.DataAnnotations . I have some validations that are specific to certain view models, so I'm comfortable with having the validation code in the same file as my models (as in the default AccountModels.cs file that ships with MVC2). But I have some common validations that apply to several models as well (valid email address format for example). When I cut/paste that validation to the second model that needs it, of course I get a duplicate definition error because they're in the same namespace (projectName.Models). So I thought of removing the common validations to a separate class within the namespace, expecting that all of my view models would be able to access the validations from there. Unexpectedly, the validations are no longer accessible. I've verified that they are still in the same namespace, and they are all public. I wouldn't expect that I would have to have any specific reference to them (tried adding using statement for the same namespace, but that didn't resolve it, and via the add references dialog, a project can't reference itself (makes sense). So any idea why public validations that have simply been moved to another file in the same namespace aren't visible to my models? CommonValidations.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Text.RegularExpressions; namespace ProjectName.Models { public class CommonValidations { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true, Inherited = true)] public sealed class EmailFormatValidAttribute : ValidationAttribute { public override bool IsValid(object value) { if (value != null) { var expression = @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"; return Regex.IsMatch(value.ToString(), expression); } else { return false; } } } } } And here's the code that I want to use the validation from: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using Growums.Models; namespace ProjectName.Models { public class PrivacyModel { [Required(ErrorMessage="Required")] [EmailFormatValid(ErrorMessage="Invalid Email")] public string Email { get; set; } } }

    Read the article

  • Best strategy for HTML partial rendering based on multiple dropdown values

    - by pv2008
    I have a View that renders something like this: "Item 1" and "Item 2" are <tr> elements from a table. After the user change "Value 1" or "Value 2" I would like to call a Controller and put the result (some HTML snippet) in the div marked as "Result of...". I have some vague notions of JQuery. I know how to bind to the onchange event of the Select element, and call the $.ajax() function, for example. But I wonder if this can be achieved in a more efficient way in ASP.NET MVC2.

    Read the article

  • Best strategy for HTML parcial rendering based on multiple dropdown values

    - by pv2008
    I have a View that renders something like this: "Item 1" and "Item 2" are <tr> elements from a table. After the user change "Value 1" or "Value 2" I would like to call a Controller and put the result (some HTML snippet) in the div marked as "Result of...". I have some vague notions of JQuery. I know how to bind to the onchage event of the Select element, and call the $.ajax() function, for example. But I wonder if this can be achieved in a more efficient way in ASP.NET MVC2.

    Read the article

  • ASP.NET MVC2 Model Validation Fails with Non-US Date Format

    - by 81bronco
    I have a small MVC2 app that displays in two cultures: en-US and es-MX. One portion contains a user input for a date that is pre-populated with the current date in the Model. When using en-US, the date field is displayed as MM/dd/yyyy and can be changed using the same format without causing any validation errors. When using es-MX, the date field is displayed as dd/MM/yyyy, but when the date is edited in this format, the server-side validation fails with the message: The value '17/05/1991' is not valid for The Date. One of the first things that jumps out at me about that message is that it is not localized. Both the message itself (which I do not think I can control) and the Display Name of the field (which I can control and is localized in my code). Should be displaying in a localized format. I have tried stepping through the code to see exactly where the validation is failing, but it seems to be happening inside some of the compiled MVC or DataAnnotations code that I cannot see. Application details: IIS6, ASP.NET 3.5 (C#), MVC 2 RTM Sample Model Code: public class TestVieModel{ [LocalizedDisplayNameDisplayName("TheDateDisplayName", NameResourceType=typeof(Resources.Model.TestViewModel))] [Required(ErrorMessageResourceName="TheDateValidationMessageRequired", ErrorMessageResourceType=typeof(Resources.Model.TestViewModel))] [DataType(DataType.Date)] public DateTime TheDate { get; set; } } Sample Controller Action Code: [HttpPost] [ValidateAntiForgeryToken] public ActionResult Save(TestViewModel model) { if(ModelState.IsValid) { // <--- Always is false when using es-MX and a date foramtted as dd/MM/yyyy. // Do other stuff return this.View("Complete", model); } // Validation failed, redisplay the form. return this.View("Enter", model); } Sample View Code: <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<HispanicSweeps.Web.Model.LosMets.EnterViewModel>" %> <!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>Test</title> </head> <body> <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div class="editor-label"> <%= Html.LabelFor(model => model.DateOfBirth) %> </div> <div class="editor-field"> <%= Html.EditorFor(model => model.DateOfBirth) %> <%= Html.ValidationMessageFor(model => model.DateOfBirth) %> </div> <p><input type="submit" value="Save" /></p> </fieldset> <% } %> </body> </html>

    Read the article

  • Issue with Autofac 2 and MVC2 using HttpRequestScoped

    - by Page Brooks
    I'm running into an issue with Autofac2 and MVC2. The problem is that I am trying to resolve a series of dependencies where the root dependency is HttpRequestScoped. When I try to resolve my UnitOfWork (which is Disposable), Autofac fails because the internal disposer is trying to add the UnitOfWork object to an internal disposal list which is null. Maybe I'm registering my dependencies with the wrong lifetimes, but I've tried many different combinations with no luck. The only requirement I have is that MyDataContext lasts for the entire HttpRequest. I've posted a demo version of the code for download here. Autofac modules are set up in web.config Global.asax.cs protected void Application_Start() { string connectionString = "something"; var builder = new ContainerBuilder(); builder.Register(c => new MyDataContext(connectionString)).As<IDatabase>().HttpRequestScoped(); builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerDependency(); builder.RegisterType<MyService>().As<IMyService>().InstancePerDependency(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); _containerProvider = new ContainerProvider(builder.Build()); IoCHelper.InitializeWith(new AutofacDependencyResolver(_containerProvider.RequestLifetime)); ControllerBuilder.Current.SetControllerFactory(new AutofacControllerFactory(ContainerProvider)); AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } AutofacDependencyResolver.cs public class AutofacDependencyResolver { private readonly ILifetimeScope _scope; public AutofacDependencyResolver(ILifetimeScope scope) { _scope = scope; } public T Resolve<T>() { return _scope.Resolve<T>(); } } IoCHelper.cs public static class IoCHelper { private static AutofacDependencyResolver _resolver; public static void InitializeWith(AutofacDependencyResolver resolver) { _resolver = resolver; } public static T Resolve<T>() { return _resolver.Resolve<T>(); } } UnitOfWork.cs public interface IUnitOfWork : IDisposable { void Commit(); } public class UnitOfWork : IUnitOfWork { private readonly IDatabase _database; public UnitOfWork(IDatabase database) { _database = database; } public static IUnitOfWork Begin() { return IoCHelper.Resolve<IUnitOfWork>(); } public void Commit() { System.Diagnostics.Debug.WriteLine("Commiting"); _database.SubmitChanges(); } public void Dispose() { System.Diagnostics.Debug.WriteLine("Disposing"); } } MyDataContext.cs public interface IDatabase { void SubmitChanges(); } public class MyDataContext : IDatabase { private readonly string _connectionString; public MyDataContext(string connectionString) { _connectionString = connectionString; } public void SubmitChanges() { System.Diagnostics.Debug.WriteLine("Submiting Changes"); } } MyService.cs public interface IMyService { void Add(); } public class MyService : IMyService { private readonly IDatabase _database; public MyService(IDatabase database) { _database = database; } public void Add() { // Use _database. } } HomeController.cs public class HomeController : Controller { private readonly IMyService _myService; public HomeController(IMyService myService) { _myService = myService; } public ActionResult Index() { // NullReferenceException is thrown when trying to // resolve UnitOfWork here. // Doesn't always happen on the first attempt. using(var unitOfWork = UnitOfWork.Begin()) { _myService.Add(); unitOfWork.Commit(); } return View(); } public ActionResult About() { return View(); } }

    Read the article

  • Getting an ASP.MVC2/VS2010 application to work in IIS 7.5

    - by Jeroen-bart Engelen
    I've recently downloaded beta 2 of VS2010 and started playing with ASP.NET MVC2. Initial development was done with Casini, but now I wanted to run the application from IIS 7.5 (I'm running Windows 7). I've installed the IIS6 metabase compatiblity and I run VS2010 as administrator so I can use the "Create Virtual Directory" button from the "Web" tab of the project settings. This created the web application entry in IIS, but it doesn't work. When I go to the main page (http://localhost/MyMvcApp/) I get a HTTP 403 error. When I go directly to one of the sub-pages (http://localhost/MyMvcApp/Home/) I get an HTTP 404. So I guess for some reason the URL routing isn't working. I've already added UrlRouting as a module and a handler to the web.config. In my searches this is offered as a solution for some similair problems. But for me this still doesn't work. The interesting part of my web.config looke like this: <system.web> <compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </assemblies> </compilation> <authentication mode="Forms"> <forms loginUrl="~/Account/LogOn" timeout="2880" /> </authentication> <membership> <providers> <clear /> <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" /> </providers> </membership> <profile> <providers> <clear /> <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" /> </providers> </profile> <roleManager enabled="false"> <providers> <clear /> <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" /> <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" /> </providers> </roleManager> <pages> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> </namespaces> </pages> <httpHandlers> <add verb="*" path="*.mvc" validate="false" type="System.Web.Mvc.MvcHttpHandler" /> </httpHandlers> <customErrors mode="Off" /> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules runAllManagedModulesForAllRequests="true" > <remove name="UrlRoutingModule"/> <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </modules> <handlers> <remove name="MvcHttpHandler" /> <add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler" /> <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </handlers> <httpErrors errorMode="Detailed" /> </system.webServer>

    Read the article

  • MVC2 EditorTemplate for DropDownList

    - by tschreck
    I've spent the majority of the past week knee deep in the new templating functionality baked into MVC2. I had a hard time trying to get a DropDownList template working. The biggest problem I've been working to solve is how to get the source data for the drop down list to the template. I saw a lot of examples where you can put the source data in the ViewData dictionary (ViewData["DropDownSourceValuesKey"]) then retrieve them in the template itself (var sourceValues = ViewData["DropDownSourceValuesKey"];) This works, but I did not like having a silly string as the lynch pin for making this work. Below is an approach I've come up with and wanted to get opinions on this approach: here are my design goals: The view model should contain the source data for the drop down list Limit Silly Strings Not use ViewData dictionary Controller is responsible for filling the property with the source data for the drop down list Here's my View Model: public class CustomerViewModel { [ScaffoldColumn(false)] public String CustomerCode{ get; set; } [UIHint("DropDownList")] [DropDownList(DropDownListTargetProperty = "CustomerCode"] [DisplayName("Customer Code")] public IEnumerable<SelectListItem> CustomerCodeList { get; set; } public String FirstName { get; set; } public String LastName { get; set; } public String PhoneNumber { get; set; } public String Address1 { get; set; } public String Address2 { get; set; } public String City { get; set; } public String State { get; set; } public String Zip { get; set; } } My View Model has a CustomerCode property which is a value that the user selects from a list of values. I have a CustomerCodeList property that is a list of possible CustomerCode values and is the source for a drop down list. I've created a DropDownList attribute with a DropDownListTargetProperty. DropDownListTargetProperty points to the property which will be populated based on the user selection from the generated drop down (in this case, the CustomerCode property). Notice that the CustomerCode property has [ScaffoldColumn(false)] which forces the generator to skip the field in the generated output. My DropDownList.ascx file will generate a dropdown list form element with the source data from the CustomerCodeList property. The generated dropdown list will use the value of the DropDownListTargetProperty from the DropDownList attribute as the Id and the Name attributes of the Select form element. So the generated code will look like this: <select id="CustomerCode" name="CustomerCode"> <option>... </select> This works out great because when the form is submitted, MVC will populate the target property with the selected value from the drop down list because the name of the generated dropdown list IS the target property. I kinda visualize it as the CustomerCodeList property is an extension of sorts of the CustomerCode property. I've coupled the source data to the property. Here's my code for the controller: public ActionResult Create() { //retrieve CustomerCodes from a datasource of your choosing List<CustomerCode> customerCodeList = modelService.GetCustomerCodeList(); CustomerViewModel viewModel= new CustomerViewModel(); viewModel.CustomerCodeList = customerCodeList.Select(s => new SelectListItem() { Text = s.CustomerCode, Value = s.CustomerCode, Selected = (s.CustomerCode == viewModel.CustomerCode) }).AsEnumerable(); return View(viewModel); } Here's my code for the DropDownListAttribute: namespace AutoForm.Attributes { public class DropDownListAttribute : Attribute { public String DropDownListTargetProperty { get; set; } } } Here's my code for the template (DropDownList.ascx): <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<SelectListItem>>" %> <%@ Import Namespace="AutoForm.Attributes"%> <script runat="server"> DropDownListAttribute GetDropDownListAttribute() { var dropDownListAttribute = new DropDownListAttribute(); if (ViewData.ModelMetadata.AdditionalValues.ContainsKey("DropDownListAttribute")) { dropDownListAttribute = (DropDownListAttribute)ViewData.ModelMetadata.AdditionalValues["DropDownListAttribute"]; } return dropDownListAttribute; } </script> <% DropDownListAttribute attribute = GetDropDownListAttribute();%> <select id="<%= attribute.DropDownListTargetProperty %>" name="<%= attribute.DropDownListTargetProperty %>"> <% foreach(SelectListItem item in ViewData.Model) {%> <% if (item.Selected == true) {%> <option value="<%= item.Value %>" selected="true"><%= item.Text %></option> <% } %> <% else {%> <option value="<%= item.Value %>"><%= item.Text %></option> <% } %> <% } %> </select> I tried using the Html.DropDownList helper, but it would not allow me to change the Id and Name attributes of the generated Select element. NOTE: you have to override the CreateMetadata method of the DataAnnotationsModelMetadataProvider for the DropDownListAttribute. Here's the code for that: public class MetadataProvider : DataAnnotationsModelMetadataProvider { protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) { var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName); var additionalValues = attributes.OfType<DropDownListAttribute>().FirstOrDefault(); if (additionalValues != null) { metadata.AdditionalValues.Add("DropDownListAttribute", additionalValues); } return metadata; } } Then you have to make a call to the new MetadataProvider in Application_Start of Global.asax.cs: protected void Application_Start() { RegisterRoutes(RouteTable.Routes); ModelMetadataProviders.Current = new MetadataProvider(); } Well, I hope this makes sense and I hope this approach may save you some time. I'd like some feedback on this approach please. Is there a better approach?

    Read the article

  • Is MVC 2 client-side validation broken in Visual Studio 2010 RC?

    - by Will
    I can't seem to get client side validation working with the version of MVC released with Visual Studio 2010 RC. I've tried it with two projects -- one upgrade from 1.0, and one using the template that came with VS. I'd think the template version would work, but it doesn't. Added the following scripts: <script type="text/javascript" src="<%= Url.Content("~/Scripts/MicrosoftMvcValidation.js") %>"> </script> <script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery.validate.js")%>"> </script> which are downloaded to the client correctly. Added the following to my form page: <% Html.EnableClientValidation(); %> <%--yes, am aware of the EndForm() bug! --%> <% using (Html.BeginForm()) { %> <%--snip --%> and I can see the client validation scripts have been added to the bottom of the form. But still client validation never happens. What is worse is that in my upgraded project, the client validation scripts are never output in the page! PLEASE NOTE: I am specifically asking about the version of MVC2 that came with VS2010 RC. Also, I do know how to google; please don't waste anybody's time searching and answering if you aren't familiar with this issue in the release candidate of Visual Studio. Thanks.

    Read the article

  • using linq to sql

    - by mazhar
    Well I am new to this orm stuff. We have to create a large project . I read about linq to sql . will it be appropiate to use it in the project of high risk . i found no problem with it personally but the thing is that there will be no going back once started.So i need some feedback from the orm gurus here at the msdn.Will entity framework will be better?( I am in doubt about link to sql because I have read and heard negative feedback here and there) I will be using mvc2 as the framework. So please give the feedback about linq to sql in this regard. q2) Also I am a fan of stored procedure as they are precomputed and fasten up the thing and I have never worked without them.I know that linq to sql support stored procedures but will it be feasible to give up stored procedure seeing the beautiful data access layer generated with little effort as we are also in a need of rapid development. q3) If some changes to some fields required in the database in Link to Sql how will the changes be accommodated in the data access layer.

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >