Search Results

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

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

  • How to update model in the database, from asp.net MVC2, using Entity Framework?

    - by Eedoh
    Hello. I'm building ASP.NET MVC2 application, and using Entity Framework as ORM. I am having troubles updating object in the database. Every time I try entity.SaveChanges(), EF inserts new line in the table, regardless of do I want update, or insert to be done. I tried attaching (like in this next example) object to entity, but then I got {"An object with a null EntityKey value cannot be attached to an object context."} Here's my simple function for inserts and updates (it's not really about vehicles, but it's simpler to explain like this, although I don't think that this effects answers at all)... public static void InsertOrUpdateCar(this Vehicles entity, Cars car) { if (car.Id == 0 || car.Id == null) { entity.Cars.AddObject(car); } else { entity.Attach(car); } entitet.SaveChanges(); } I even tried using AttachTo("Cars", car), but I got the same exception. Anyone has experience with this?

    Read the article

  • Which datagrid to use for ASP.NET MVC2 project?

    - by Nick
    Hi, I am developing a commercial MVC2 app that requires a grid that has callback update in some form to support 10,000+ rows. It should also support relatively rich content (icons, multiline descriptions etc). Although it requires the usual paging/scrolling/sorting features it does not need support for grouping. So nothing that special. The commercial grids I looked at were Component Art (http://www.componentart.com/products/aspnetmvc/datagrid/) and Telerik (http://www.telerik.com/products/aspnet-mvc/grid.aspx) which both look pretty good but may be a little OTT for what I need. They are also $800 and $999 respectively (1 developer). I've also looked at jqGrid (http://www.trirand.net/download.aspx) and the grid from MvcContrib. These appear ok but for a commercial app I am concerned that these may be risky options - though could be wrong there. I'd really appreciate any views/exprience on either the above grids or perhaps you can suggest a better option/approach. FYI I am using EF4 and C#. Cheers

    Read the article

  • Best practice for submits redirecting to another page in MVC2?

    - by blesh
    I have a situation with my MVC2 app where I have multiple pages that need to submit different information, but all need to end up at the same page. In my old Web Forms app, I'd have just accomplished this in my btnSave_Click delegate with a Redirect. There are three different types of products, each of which need to be saved to the cart in a completely different manner from their completely different product pages. I'm not going to get into why or how they're different, just suffice to say, they're totally different. After they're saved to the cart, I need to "redirect" to the Checkout view. But it should be noted, that you can also just browse straight to the Checkout view without having to submit any products to add to the cart. Here's a diagram of what I'm trying to accomplish, and how I think I need to handle it: Is this correct? It seems like a common scenario, but I haven't seen any examples of how I should handle this. Thank you all in advance.

    Read the article

  • ASP.Net MVC2 Client and Server Validation sharing the same code - is it possible?

    - by RemotecUk
    With the excellent XVal by Steve Sanderson, it is possible to tell the client side validation to post the value being validated to the server using jquery. A method on the server then uses the same server side code you use for your server side validation, and returns simply a true or false to determine if the field is valid. The advantage of this method is that you write your complex validation logic once in C# code and then put some JQuery plumbing in to tell your client page where to go to access your server validation. I have been reading some blogs on MVC2 but no one seems to mention this functionality. Is it possible to tell the Microsoft MVC validation javascript to call a url validate data? Or do you have to write your own client side validation routines. I should note that using the xVal method a custom validation to say if an email address is in use or not can be run from the client via a JQuery post which accesses the server side validation logic.

    Read the article

  • In MVC2, how do I validate fields that aren't in my data model?

    - by Andy Evans
    I am playing with MVC2 in VS 2010 and am really getting to like it. In a sandbox application that I've started from scratch, my database is represented in an ADO.NET entity data model and have done much of the validation for fields in my data model using Scott Guthrie's "buddy class" approach which has worked very well. However, in a user registration form that I have designed and am experimenting with, I'd like to add a 'confirm email address' or a 'confirm password' field. Since these fields obviously wouldn't exist in my data model, how would I validate these fields client side and server side? I would like to implement something like 'Html.ValidationMessageFor', but these fields don't exist in the data model. Any help would be greatly appreciated.

    Read the article

  • Does Anyone Know Of A Solid Web Example Using ASP.NET MVC1 or MVC2, NHibernate, Fluent NHibernate &

    - by Sara
    I am looking for solid non-console examples of how to use ASP.NET MVC1 or MVC2, NHibernate, Fluent NHibernate & Castle. I looked at Sharp Architecture and its just too much to digest for my newbie mind. I need a clean, clear, concise Step A, Step B, Step C tutorial or a solid example that is a web application and not a console application. I have searched and searched and searched and I have found incomplete examples (examples with just enough information to make me say where does that code go), console applications and no good web application examples. Does anyone know of a COMPLETE web example? If I see another console example, I'm going to scream....

    Read the article

  • How to send link/url to confirm user registration and/or password reset/recovery using ASP.Net MVC2?

    - by Mark_DVM_Software
    Hi, I see it all over the place, yet, I could not find one example about this (maybe I don't know the proper wording), I am trying to build using ASP .Net MVC2 (but any example on just ASP .Net would be also helpful) a process that will send a link to the user at the end of the registration process to let him confirm his registration. Also, a similar process to let the user to reset his password, with the typical "forgot password" and send a link/url so that the user can click and type a new password. Can someone help me to either find an example or at least to let me know how to "google" it? Thanks, Mark

    Read the article

  • ASP.Net MVC2 CustomModelBinder not working... Changed from MVC1

    - by Ian
    (My apologies if this seems verbose - trying to provide all relevant code) I've just upgraded to VS2010, and am now having trouble trying to get a new CustomModelBinder working. In MVC1 I would have written something like public class AwardModelBinder: DefaultModelBinder { : public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { // do the base binding to bind all simple types Award award = base.BindModel(controllerContext, bindingContext) as Award; // Get complex values from ValueProvider dictionary award.EffectiveFrom = Convert.ToDateTime(bindingContext.ValueProvider["Model.EffectiveFrom"].AttemptedValue.ToString()); string sEffectiveTo = bindingContext.ValueProvider["Model.EffectiveTo"].AttemptedValue.ToString(); if (sEffectiveTo.Length > 0) award.EffectiveTo = Convert.ToDateTime(bindingContext.ValueProvider["Model.EffectiveTo"].AttemptedValue.ToString()); // etc return award; } } Of course I'd register the custom binder in Global.asax.cs: protected void Application_Start() { RegisterRoutes(RouteTable.Routes); // register custom model binders ModelBinders.Binders.Add(typeof(Voucher), new VoucherModelBinder(DaoFactory.UserInstance("EH1303"))); ModelBinders.Binders.Add(typeof(AwardCriterion), new AwardCriterionModelBinder(DaoFactory.UserInstance("EH1303"), new VOPSDaoFactory())); ModelBinders.Binders.Add(typeof(SelectedVoucher), new SelectedVoucherModelBinder(DaoFactory.UserInstance("IT0706B"))); ModelBinders.Binders.Add(typeof(Award), new AwardModelBinder(DaoFactory.UserInstance("IT0706B"))); } Now, in MVC2, I'm finding that my call to base.BindModel returns an object where everything is null, and I simply don't want to have to iterate all the form fields surfaced by the new ValueProvider.GetValue() function. Google finds no matches for this error, so I assume I'm doing something wrong. Here's my actual code: My domain object (infer what you like about the encapsulated child objects - I know I'll need custom binders for those too, but the three "simple" fields (ie. base types) Id, TradingName and BusinessIncorporated are also coming back null): public class Customer { /// <summary> /// Initializes a new instance of the Customer class. /// </summary> public Customer() { Applicant = new Person(); Contact = new Person(); BusinessContact = new ContactDetails(); BankAccount = new BankAccount(); } /// <summary> /// Gets or sets the unique customer identifier. /// </summary> public int Id { get; set; } /// <summary> /// Gets or sets the applicant details. /// </summary> public Person Applicant { get; set; } /// <summary> /// Gets or sets the customer's secondary contact. /// </summary> public Person Contact { get; set; } /// <summary> /// Gets or sets the trading name of the business. /// </summary> [Required(ErrorMessage = "Please enter your Business or Trading Name")] [StringLength(50, ErrorMessage = "A maximum of 50 characters is permitted")] public string TradingName { get; set; } /// <summary> /// Gets or sets the date the customer's business began trading. /// </summary> [Required(ErrorMessage = "You must supply the date your business started trading")] [DateRange("01/01/1900", "01/01/2020", ErrorMessage = "This date must be between {0} and {1}")] public DateTime BusinessIncorporated { get; set; } /// <summary> /// Gets or sets the contact details for the customer's business. /// </summary> public ContactDetails BusinessContact { get; set; } /// <summary> /// Gets or sets the customer's bank account details. /// </summary> public BankAccount BankAccount { get; set; } } My controller method: /// <summary> /// Saves a Customer object from the submitted application form. /// </summary> /// <param name="customer">A populate instance of the Customer class.</param> /// <returns>A partial view indicating success or failure.</returns> /// <httpmethod>POST</httpmethod> /// <url>/Customer/RegisterCustomerAccount</url> [HttpPost] [ValidateAntiForgeryToken] public ActionResult RegisterCustomerAccount(Customer customer) { if (ModelState.IsValid) { // save the Customer // return indication of success, or otherwise return PartialView(); } else { ViewData.Model = customer; // load necessary reference data into ViewData ViewData["PersonTitles"] = new SelectList(ReferenceDataCache.Get("PersonTitle"), "Id", "Name"); return PartialView("CustomerAccountRegistration", customer); } } My custom binder: public class CustomerModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { ValueProviderResult vpResult = bindingContext .ValueProvider.GetValue(bindingContext.ModelName); // vpResult is null // MVC2 - ValueProvider is now an IValueProvider, not dictionary based anymore if (bindingContext.ValueProvider.GetValue("Model.Applicant.Title") != null) { // works } Customer customer = base.BindModel(controllerContext, bindingContext) as Customer; // customer instanitated with null (etc) throughout return customer; } } My binder registration: /// <summary> /// Application_Start is called once when the web application is first accessed. /// </summary> protected void Application_Start() { RegisterRoutes(RouteTable.Routes); // register custom model binders ModelBinders.Binders.Add(typeof(Customer), new CustomerModelBinder()); ReferenceDataCache.Populate(); } ... and a snippet from my view (could this be a prefix problem?) <div class="inputContainer"> <label class="above" for="Model_Applicant_Title" accesskey="t"><span class="accesskey">T</span>itle<span class="mandatoryfield">*</span></label> <%= Html.DropDownList("Model.Applicant.Title", ViewData["PersonTitles"] as SelectList, "Select ...", new { @class = "validate[required]" })%> <% Html.ValidationMessageFor(model => model.Applicant.Title); %> </div> <div class="inputContainer"> <label class="above" for="Model_Applicant_Forename" accesskey="f"><span class="accesskey">F</span>orename / First name<span class="mandatoryfield">*</span></label> <%= Html.TextBox("Model.Applicant.Forename", Html.Encode(Model.Applicant.Forename), new { @class = "validate[required,custom[onlyLetter],length[2,20]]", title="Enter your forename", maxlength = 20, size = 20, autocomplete = "off", onkeypress = "return maskInput(event,re_mask_alpha);" })%> </div> <div class="inputContainer"> <label class="above" for="Model_Applicant_MiddleInitials" accesskey="i">Middle <span class="accesskey">I</span>nitial(s)</label> <%= Html.TextBox("Model.Applicant.MiddleInitials", Html.Encode(Model.Applicant.MiddleInitials), new { @class = "validate[optional,custom[onlyLetter],length[0,8]]", title = "Please enter your middle initial(s)", maxlength = 8, size = 8, autocomplete = "off", onkeypress = "return maskInput(event,re_mask_alpha);" })%> </div>

    Read the article

  • ASP.NET MVC2 and MemberShipProvider: How well do they go together?

    - by Sparhawk
    I have an existing ASP.NET application with lots of users and a large database. Now I want to have it in MVC 2. I do not want to migrate, I do it more or less from scratch. The database I want to keep and not touch too much. I already have my database tables and I also want to keep my LINQ to SQL-Layer. I didn't use a MembershipProvider in my current implementation (in ASP.NET 1.0 that wasn't strongly supported). So, either I write my own Membershipprovider to meet the needs of my database and app or I don't use the membershipprovider at all. I'd like to understand the consequences if I don't use the membership provider. What is linked to that? I understand that in ASP.NET the Login-Controls are linked to the provider. The AccountModel which is automatically generated with MVC2 could easily be changed to support my existing logic. What happens when a user is identified by a an AuthCookie? Does MVC use the MembershipProvider then? Am I overlooking something? I have the same questions regarding RoleProvider. Input is greatly appreciated.

    Read the article

  • Why would he say "We don't want to support MVC3"?

    - by MadBurn
    I work in a small shop at a fairly big company doing intranet web applications. By small, I mean there is 1 other guy in my position... and he graduated with me last December. (we aren't the only IT, but the only ones in our field) We are switching out an old COBOL system and converting it's only used application suite to a Web App. My company has contracted to a Web Application firm to help with this process who has chosen ASP.NET MVC, during one of the important meetings I asked if they will be using MVC2 or MVC3. Their lead developer said: "MVC2, we don't want to support MVC3. haha" My question is, why is this? This was several months ago and I've been doing extensive and self training gearing up for the MVC switch. From everything I am understanding, MVC3 is just like MVC2 if you don't use Razor and it fixes a number of smaller bugs that MVC2 had. So in my eyes, I can't see any reason to NOT use MCV3. There has to be something I'm missing. Since I don't really have any mentors to turn to in the real world, I'm coming here. What problems are there with MVC3 that might possibly lead him to say this that I'm missing?

    Read the article

  • How to use and/or localize DisplayAttribute with ASP.NET MVC2?

    - by asp_net
    I am trying to figure out how to get the DisplayAttribute in my MVC 2 ViewModel to work with the Html.LabelFor() helper. Neither public class TestModel { [Display(ResourceType = typeof(Localization.Labels))] public string Text { get; set; } } nor public class TestModel { [Display(Name = "test")] public string Text { get; set; } } seem to work. Localizing the Required Attribute works as expected: [Required(ErrorMessageResourceName = "Test", ErrorMessageResourceType = typeof(Localization.Labels))] I am using VS2010 RC. Has anybody got that running?

    Read the article

  • ASP.NET MVC2 RC : How to intercept or trigger client-side validation before ajax request?

    - by jacko
    I have a username textbox on a form, that has a few validation rules applied to it via the DataAnnotation attributes: [Required(ErrorMessage = "FTP login is required")] [StringLength(15, ErrorMessage = "Must be 15 characters or fewer")] [RegularExpression(@"[a-zA-Z0-9]*", ErrorMessage = "Alpha-numeric characters only")] public string FtpLogin { get; set; } I also have a button next to this text box, that fires off a jQuery ajax request that checks for the existence of the username as follows: <button onclick="check(this);return false;" id="FtpLoginCheck" name="FtpLoginCheck">Available?</button> I'm looking for a way of tieing the two together, so that the client-side validation is performed before the call to the "check(this)" in the onclick event. Edit: To be more clear, I need a way to inspect or trigger the client-side validation result of the textbox, when I click the unrelated button beside it. Edit: I now have the button JS checking for $("form").validate().invalid, but not displaying the usual validation messages. Almost there Any ideas?

    Read the article

  • ASP.NET MVC2 - Does Html.EnableClientValidation() work on the nested data model?

    - by warmcold
    I have seen the client side validation examples and videos on internet by using Html.EnableClientValidation(). But all target on the simple data model. Does the Html.EnableClientValidation() work on the nested data model like below? public class Person { public Name Name { get; set; } public string Gender { get; set; } } public class Name { public string First { get; set; } public string Last { get; set; } }

    Read the article

  • mvc2 host on iis6 : The incoming request does not match any route.

    - by Sefer KILIÇ
    I have to host my project on iis6, I can not change iis setting on server. So, I modified global.asax like below. But when I browse project I got error like : The incoming request does not match any route. have any idea? thanks public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute("Default", // Route name "{controller}.aspx/{action}/{id}", new { controller = "Home", action = "Index", id = "" } // Parameter defaults ) ); routes.MapRoute("Detail", // Route name "{controller}.aspx/{action}/{id}/{sid}", new { controller = "Home", action = "Index", id = "", sid="" } // Parameter defaults ) ); routes.MapRoute("ForGoogle", // Route name "{controller}.aspx/{action}/{friendlyUrl}/{id}/{partialName}", new { controller = "Home", action = "Index", friendlyUrl = "", id = "", partialName =""} // Parameter defaults ) ); routes.MapRoute( "PostFeed", "Feed/{type}", new { controller = "Product", action = "PostFeed", type = "rss" } ); }

    Read the article

  • Showing Different fields in EditorForModel vs. DisplayForModel modes in MVC2

    - by CodeGrue
    I have a viewmodel that has an int StateID field and a string StateName field like so: public class DepartmentViewModel : BaseViewModel, IModelWithId { // only show in edit mode public int StateId { get; set; } // only show in display mode public string StateName { get; set; } } I have a read only view that uses DisplayForModel and an update view that uses EditorForModel. I want the DisplayForModel view to show the StateName property, and the EditorForModel view use the StateID property (I am actually rendering a dropdownlist based on this). I have not been able to figure out how to decorate my viewmodel properties to create this behavior.

    Read the article

  • Is there a way to update a ViewModel in MVC2?

    - by Juvaly
    This code works: [HttpPost] public ActionResult Edit(int id, FormCollection fc) { Movie movie = ( from m in _ctx.Movie.Include("MovieActors") where m.MovieID == id select m ).First(); MovieActorViewModel movieActor = new MovieActorViewModel(movie); if (TryUpdateModel(movieActor)) { _ctx.ApplyPropertyChanges(movieActor.Movie.EntityKey.EntitySetName, movieActor.Movie); _ctx.SaveChanges(); } return View(movieActor); } However, I am not sure how to test this, and in general would much rather have the method take a typed model like: [HttpPost] public ActionResult Edit(MovieActorViewModel movieActor) Is this possible? What changes to my MovieActorViewModel class do I need to make in order to enable this? That class looks like this: public class MovieActorViewModel { public Movie Movie { get; set; } public Actor Actor { get; set; } public PublisherDealViewModel(Movie movie) { this.Movie = movie; this.Actor = ( from a in this.Movie.Actors where a.ActorID == 1 select a ).First(); } } The view is typed (inherits ViewPage) simple: <% using (Html.BeginForm()) {%> Movie Title: <%= Html.TextBoxFor(model=>model.Movie.Title) %><br/> Actor Name: <%= Html.TextBoxFor(model=>model.Actor.Name) %> <% } %>

    Read the article

  • NerdDinner form validation DataAnnotations ERROR in MVC2 when a form field is left blank.

    - by Edward Burns
    Platform: Windows 7 Ultimate IDE: Visual Studio 2010 Ultimate Web Environment: ASP.NET MVC 2 Database: SQL Server 2008 R2 Express Data Access: Entity Framework 4 Form Validation: DataAnnotations Sample App: NerdDinner from Wrox Pro ASP.NET MVC 2 Book: Wrox Professional MVC 2 Problem with Chapter 1 - Section: "Integrating Validation and Business Rule Logic with Model Classes" (pages 33 to 35) ERROR Synopsis: NerdDinner form validation ERROR with DataAnnotations and db nulls. DataAnnotations in sample code does not work when the database fields are set to not allow nulls. ERROR occurs with the code from the book and with the sample code downloaded from codeplex. Help! I'm really frustrated by this!! I can't believe something so simple just doesn't work??? Steps to reproduce ERROR: Set Database fields to not allow NULLs (See Picture) Set NerdDinnerEntityModel Dinner class fields' Nullable property to false (See Picture) Add DataAnnotations for Dinner_Validation class (CODE A) Create Dinner repository class (CODE B) Add CREATE action to DinnerController (CODE C) This is blank form before posting (See Picture) This null ERROR occurs when posting a blank form which should be intercepted by the Dinner_Validation class DataAnnotations. Note ERROR message says that "This property cannot be set to a null value. WTH??? (See Picture) The next ERROR occurs during the edit process. Here is the Edit controller action (CODE D) This is the "Edit" form with intentionally wrong input to test Dinner Validation DataAnnotations (See Picture) The ERROR occurs again when posting the edit form with blank form fields. The post request should be intercepted by the Dinner_Validation class DataAnnotations. Same null entry error. WTH??? (See Picture) See screen shots at: http://www.intermedia4web.com/temp/nerdDinner/StackOverflowNerdDinnerQuestionshort.png CODE A: [MetadataType(typeof(Dinner_Validation))] public partial class Dinner { } [Bind(Include = "Title, EventDate, Description, Address, Country, ContactPhone, Latitude, Longitude")] public class Dinner_Validation { [Required(ErrorMessage = "Title is required")] [StringLength(50, ErrorMessage = "Title may not be longer than 50 characters")] public string Title { get; set; } [Required(ErrorMessage = "Description is required")] [StringLength(265, ErrorMessage = "Description must be 256 characters or less")] public string Description { get; set; } [Required(ErrorMessage="Event date is required")] public DateTime EventDate { get; set; } [Required(ErrorMessage = "Address is required")] public string Address { get; set; } [Required(ErrorMessage = "Country is required")] public string Country { get; set; } [Required(ErrorMessage = "Contact phone is required")] public string ContactPhone { get; set; } [Required(ErrorMessage = "Latitude is required")] public double Latitude { get; set; } [Required(ErrorMessage = "Longitude is required")] public double Longitude { get; set; } } CODE B: public class DinnerRepository { private NerdDinnerEntities _NerdDinnerEntity = new NerdDinnerEntities(); // Query Method public IQueryable<Dinner> FindAllDinners() { return _NerdDinnerEntity.Dinners; } // Query Method public IQueryable<Dinner> FindUpcomingDinners() { return from dinner in _NerdDinnerEntity.Dinners where dinner.EventDate > DateTime.Now orderby dinner.EventDate select dinner; } // Query Method public Dinner GetDinner(int id) { return _NerdDinnerEntity.Dinners.FirstOrDefault(d => d.DinnerID == id); } // Insert Method public void Add(Dinner dinner) { _NerdDinnerEntity.Dinners.AddObject(dinner); } // Delete Method public void Delete(Dinner dinner) { foreach (var rsvp in dinner.RSVPs) { _NerdDinnerEntity.RSVPs.DeleteObject(rsvp); } _NerdDinnerEntity.Dinners.DeleteObject(dinner); } // Persistence Method public void Save() { _NerdDinnerEntity.SaveChanges(); } } CODE C: // ************************************** // GET: /Dinners/Create/ // ************************************** public ActionResult Create() { Dinner dinner = new Dinner() { EventDate = DateTime.Now.AddDays(7) }; return View(dinner); } // ************************************** // POST: /Dinners/Create/ // ************************************** [HttpPost] public ActionResult Create(Dinner dinner) { if (ModelState.IsValid) { dinner.HostedBy = "The Code Dude"; _dinnerRepository.Add(dinner); _dinnerRepository.Save(); return RedirectToAction("Details", new { id = dinner.DinnerID }); } else { return View(dinner); } } CODE D: // ************************************** // GET: /Dinners/Edit/{id} // ************************************** public ActionResult Edit(int id) { Dinner dinner = _dinnerRepository.GetDinner(id); return View(dinner); } // ************************************** // POST: /Dinners/Edit/{id} // ************************************** [HttpPost] public ActionResult Edit(int id, FormCollection formValues) { Dinner dinner = _dinnerRepository.GetDinner(id); if (TryUpdateModel(dinner)){ _dinnerRepository.Save(); return RedirectToAction("Details", new { id=dinner.DinnerID }); } return View(dinner); } I have sent Wrox and one of the authors a request for help but have not heard back from anyone. Readers of the book cannot even continue to finish the rest of chapter 1 because of these errors. Even if I download the latest build from Codeplex, it still has the same errors. Can someone please help me and tell me what needs to be fixed? Thanks - Ed.

    Read the article

  • ASP.NET MVC2: Can you get ModelMetadata.ContainerType from within a collection?

    - by CodeSponge
    I'm trying to call DisplayFor and DisplayForModel to iterate an IEnumerable< with various element types from within a view. I have Templates defined for each element/Model type. What I would like to do is check the ViewData.ModelMetadata.ContainerType from within the Template so that Template can determine if it was called as part of a collection. A simple example: Index1.aspx: To render a collection of Foos. <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Foo>>" %> <asp:Content ContentPlaceHolderID="MainPlaceHolder" runat="server"> <ul><%:Html.DisplayForModel()%></ul> </asp:Content> Index2.aspx: To render a Foo. <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Foo>" %> <asp:Content ContentPlaceHolderID="MainPlaceHolder" runat="server"> <%:Html.DisplayForModel()%> </asp:Content> Shared\DisplayTemplates\Foo.ascx: A context aware Template for Foo. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Foo>" %> <% var tag = typeof(IEnumerable).IsAssignableFrom(ViewData.ModelMetaData.ContainerType) ? "li" : "div"; %> <<%:tag%>><%:Model.Name%></<%:tag%>> The problem with this example is that ViewData.ModelMetaData.ContainerType is null in the Template when resolved though Index1.aspx. From what I've read on Brad Wilson post and others it has to do with the use of IEnumerable and its being an interface. Is there a way to insure that the ContainerType is set? Perhaps by creating a ModelMetadataProviders? I looked into that breifly but it appears the ContainerType value is determined before and then passed to the Provider. Any suggestions would be appreciated.

    Read the article

  • How can I make this Route (ASP.Net MVC2) ?

    - by Felipe
    Hi All, I'm begginer in asp.net mvc and I have some doutbs about routes. Im' developing a system to manage documents and I need make an URL like this: routes.MapRoute("Documentos", "{controller}/{documentType}/{documento}/{action}/{id}", new { controller = "Home", documentType = "", documento = "", action = "Index", id = UrlParameter.Optional }); and the app working an URL like theses: "Document/Administrative/Contract" - (Index action by default to list documents of type 'Contract') "Document/Administrative/Contract/New" - (new action in controller) "Document/Administrative/Contract/10" - (detail action in controller) "Document/Administrative/Contract/Edit/10" - (edit action in controller) Document would be a Controller, and Administrative would be just a description in url to identify that documents of 'Contract' is Administrative... So, My doubts is about my controllers and actions, How should be the signature of the methods of controller ? Need I make an Area called Documents to do this more easy ? PS: Sorry for my english! Thanks a lot, Cheers! Felipe

    Read the article

  • How can I send a GET request containing a colon, to an ASP.NET MVC2 controller?

    - by Cheeso
    This works fine: GET /mvc/Movies/TitleIncludes/Lara%20Croft When I submit a request that contains a colon, like this: GET /mvc/Movies/TitleIncludes/Lara%20Croft:%20Tomb ...it generates a 400 error. The error says ASP.NET detected invalid characters in the URL. If I try url-escaping, the request looks like this: GET /mvc/Movies/TitleIncludes/Lara%20Croft%3A%20Tomb ...and this also gives me a 400 error. If I replace the colon with a | : GET /mvc/Movies/TitleIncludes/Lara%20Croft|%20Tomb ..that was also rejeted as illegal, this time with a 500 error. The message: Illegal characters in path. URL-escaping that | results in the same error. I really, really don't want to use a querystring parameter. related: Sending URLs/paths to ASP.NET MVC controller actions

    Read the article

  • What is the correct way to create dynamic javascript in ASP.net MVC2?

    - by sabbour
    I'm creating a Google Maps partial view/user control in my project that is passed a strongly typed list of objects containing latitude and longitude values. Currently, this is the code I have for the partial: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Project.Models.Entities.Location>>" %> <!-- Place for google to put the map --> <div id="report_map_canvas" style="width: 100%; height: 728px; margin-bottom: 2px;"> </div> <script type='text/javascript'> google.load("maps", "2"); $(document).ready(initializeMap); function initializeMap() { if (GBrowserIsCompatible()) { var map = new GMap2(document.getElementById('report_map_canvas')); map.setCenter(new GLatLng(51.5, -0.1167), 2); <% foreach (var item in Model) { %> map.addOverlay(new GMarker(new GLatLng('<%= Html.Encode(item.latitude)%>','<%= Html.Encode(item.longitude)%>'),{ title: '<%= Html.Encode(String.Format("{0:F}",item.speed)) %> km/h '})); <% } %> map.setUIToDefault(); } } </script> Is it right to dynamically create the javascript file this way by looping over the list and emitting javascript? Is there a better way to do it?

    Read the article

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