Search Results

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

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

  • using linq to sql

    - by user324831
    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

  • I'm getting a "Does not implement IController" error on images and robots.txt in MVC2

    - by blesh
    I'm getting a strange error on my webserver for seemingly every file but the .aspx files. Here is an example. Just replace '/robots.txt' with any .jpg name or .gif or whatever and you'll get the idea: The controller for path '/robots.txt' was not found or does not implement IController. I'm sure it's something to do with how I've setup routing but I'm not sure what exactly I need to do about it. Also, this is a mixed MVC and WebForms site, if that makes a difference.

    Read the article

  • ViewModel with SelectList binding in ASP.NET MVC2

    - by Junto
    I am trying to implement an Edit ViewModel for my Linq2SQL entity called Product. It has a foreign key linked to a list of brands. Currently I am populating the brand list via ViewData and using DropDownListFor, thus: <div class="editor-field"> <%= Html.DropDownListFor(model => model.BrandId, (SelectList)ViewData["Brands"])%> <%= Html.ValidationMessageFor(model => model.BrandId) %> </div> Now I want to refactor the view to use a strongly typed ViewModel and Html.EditorForModel(): <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <%=Html.EditorForModel() %> <p> <input type="submit" value="Save" /> </p> </fieldset> <% } %> In my Edit ViewModel, I have the following: public class EditProductViewModel { [HiddenInput] public int ProductId { get; set; } [Required()] [StringLength(200)] public string Name { get; set; } [Required()] [DataType(DataType.Html)] public string Description { get; set; } public IEnumerable<SelectListItem> Brands { get; set; } public int BrandId { get; set; } public EditProductViewModel(Product product, IEnumerable<SelectListItem> brands) { this.ProductId = product.ProductId; this.Name = product.Name; this.Description = product.Description; this.Brands = brands; this.BrandId = product.BrandId; } } The controller is setup like so: public ActionResult Edit(int id) { BrandRepository br = new BrandRepository(); Product p = _ProductRepository.Get(id); IEnumerable<SelectListItem> brands = br.GetAll().ToList().ToSelectListItems(p.BrandId); EditProductViewModel model = new EditProductViewModel(p, brands); return View("Edit", model); } The ProductId, Name and Description display correctly in the generated view, but the select list does not. The brand list definitely contains data. If I do the following in my view, the SelectList is visible: <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <%=Html.EditorForModel() %> <div class="editor-label"> <%= Html.LabelFor(model => model.BrandId) %> </div> <div class="editor-field"> <%= Html.DropDownListFor(model => model.BrandId, Model.Brands)%> <%= Html.ValidationMessageFor(model => model.BrandId) %> </div> <p> <input type="submit" value="Save" /> </p> </fieldset> <% } %> What am I doing wrong? Does EditorForModel() not generically support the SelectList? Am I missing some kind of DataAnnotation? I can't seem to find any examples of SelectList usage in ViewModels that help. I'm truly stumped. This answer seems to be close, but hasn't helped.

    Read the article

  • ASP.NET MVC2 on GoDaddy

    - by MVCDummy09
    I've talked to GoDaddy several times but no one there knows what they're talking about. I'm creating a simple web site for a local company who uses GoDaddy Windows Shared hosting and I'd like to create the project using MVC version 2. The first time the guy said he hadn't heard of MVC and that GoDaddy doesn't support it. The second time I called they said they only support MVC on dedicated hosting and he wasn't sure about MVC 2 specifically. The third time I called the guy said I could run MVC 2 on shared hosting. Anyone that actually has experience know?

    Read the article

  • DRY Validation with MVC2

    - by Matthew
    Hi All, I'm trying to figure out how I can define validation rules for my domain objects in one single location within my application but have run in to a snag... Some background: My location has several parts: - Database - DAL - Business Logic Layer - SOAP API Layer - MVC website The MVC website accesses the database via the SOAP API, just as third parties would. We are using server and and client side validation on the MVC website as well as in the SOAP API Layer. To avoid having to manually write client side validation we are implementing strongly typed views in conjunction with the Html.TextBoxFor and Html.ValidationMessageFor HTML helpers, as shown in Step 3 here. We also create custom models for each form where one form takes input for multiple domain objects. This is where the problem begins, the HTML helpers read from the model for the data annotation validation attributes. In most cases our forms deal with multiple domain objects and you can't specify more than one type in the <%@Page ... Inherits="System.Web.Mvc.ViewPage" % page directive. So we are forced to create a custom model class, which would mean duplicating validation attributes from the domain objects on to the model class. I've spent quite some time looking for workarounds to this, such has referencing the same MetadataType from both the domain class and the custom MVC models, but that won't work for several reasons: You can only specify one MetadataType attribute per class, so its a problem if a model references multiple domain objects, each with their own metadata type. The data annotation validation code throws an exception if the model class doesn't contain a property that is specified in the referenced MetadataType which is a problem with the model only deals with a subset of the properties for a given domain object. I've looked at other solutions as well but to no avail. If anyone has any ideas on how to achieve a single source for validation logic that would work across MVC client and server side validation functionality and other locations (such as my SOAP API) I would love to hear it! Thanks in advance, Matthew

    Read the article

  • Ajax comments form in ASP.NET MVC2

    - by Artiom Chilaru
    I've been playing around with different aspects of MVC for some time now, and I've reached a situation where I'm not sure what would be the best way to solve a problem. I'm hoping that the SO community will help me out here :P I've seen a number of examples of Ajax.BeginForm on the internet, and it seems like a very nifty idea. E.g. you have a dropdown where you select a customer - and on selecting one it will load this client's details in some placeholder on the page. This works perfectly fine. But what to do if you want to tie in some validation in the box? Just hypothetically, imagine an article page, and user comments in the bottom. Below the comments area there's an ajax-y "Add comment" box. When a user adds a comment, it will appear in the comments area, below the last comment there. If I set the Ajax.BeginForm to Append the result of the call to the Comments area, it will work fine. But what if the data posted is not valid? Instead of appending a "successful" comment to the comments area I have to show the user validation errors. At this point I decided that the area INSIDE the Ajax.BeginForm will be inside a partial, and the form's submits will return this partial. Validation works fine. On each submit we reload the contents inside the form element. But how to add the successful comment to the top? Other things to consider: The comment form also has a "Preview" button. When the user clicks on Preview, I should load the rendered comment into a preview box. This will probably be inside the form area as well. I was thinking of using Json results instead. When the user submits the form, the server code will generate a Json object with a Success value, and html rendered partials as some properties. Something like { "success": true, "form": "<html form data>", "comment": "successful comment html to inject into the page" } This would be a perfect solution, except there's no way in MVC to render a partial into a string, inside the controller (separation of context, remember?). So.. what should I do then? Any "correct" way to implement this?

    Read the article

  • MVC2 client/server validation of DateTime/Date using DataAnnotations

    - by Thomas
    The following are true: One of my columns (BirthDate) is of type Date in SQL Server. This very same column (BirthDate) is of type DateTime when EF generates the model. I am using JQuery UI Datepicker on the client side to be able to select the BirthDate. I have the following validation logic in my buddy class: [Required(ErrorMessageResourceType = typeof(Project.Web.ValidationMessages), ErrorMessageResourceName = "Required")] [RegularExpression(@"\b(0?[1-9]|1[012])[/](0?[1-9]|[12][0-9]|3[01])[/](19|20)?[0-9]{2}\b", ErrorMessageResourceType = typeof(Project.Web.ValidationMessages), ErrorMessageResourceName = "Invalid")] public virtual DateTime? BirthDate { get; set; } There are two issues with this: This will not pass server side validation (if I enable client side validation it works just fine). I am assuming that this is because the regular expression doesn't take into account hours, minutes, seconds as the value in the text box has already been cast as a DateTime on the server by the time validation occurs. If data already exists in the database and is read into the model and displayed on the page the BirthDate field shows hours, minutes, seconds in my text box (which I don't want). I can always use ToShortDateString() but I am wondering if there is some cleaner approach that I might be missing. Thanks

    Read the article

  • Calling a MVC2 partial view using jquery returns empty string problem

    - by Jason
    I have an issue where I have a partial view that returns some HTML to be displayed. Its called when something is clicked on the page using jquery. The problem is that no matter how I call it, i get back an empty string even though it reports success. This is happening to me using Chrome, going against my local machine. My controller looks like this: public ActionResult MyPartialView() { return PartialView(model); } I have tried jquery using .get(), .post() and .load() and all have the same results. Here is an example using .post(): $.post(url, function (data) { alert(data); }); The result always comes back as an empty string. I can navigate to the partial view in the browser manually and i get back the desired HTML. The URL I am using to call it I resolved fully so it looks like "http://localhost/controller/mypartialview" rather than using the relative path of "/controller/mypartialview" which I thought was the original problem. Any idea what may cause this?

    Read the article

  • Spark-View-Engine with ASP.NET MVC2

    - by Ben
    How do you modify a ASP.NET MVC 2.0 project to work with the Spark View Engine? I tried like described here: http://dotnetslackers.com/articles/aspnet/installing-the-spark-view-engine-into-asp-net-mvc-2-preview-2.aspx But somehow it still tries to route to .aspx files. Here the code of my global.asax: public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); } protected void Application_Start() { SparkViewFactory svf = new SparkViewFactory(); PrecompileViews(svf); AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } public static void PrecompileViews(SparkViewFactory svf) { var controllerFactory = svf; var viewFactory = new SparkViewFactory(controllerFactory.Settings); var batch = new SparkBatchDescriptor(); batch .For<HomeController>() .For<AccountController>(); viewFactory.Precompile(batch); } } }

    Read the article

  • asp.net mvc2 - controller for master page and code organization

    - by ile
    I've just finished my first ASP.NET MVC (2) CMS. Next step is to build website that will show data from CMS's database. This is website design: #1 (Red box) - displays article categories. ViewModel: public class CategoriesDisplay { public CategoriesDisplay() { } public int CategoryID { set; get; } public string CategoryTitle { set; get; } } #2 (Brown box) - displays last x articles; skips those from green box #3. Viewmodel: public class ArticleDisplay { public ArticleDisplay() { } public int CategoryID { set; get; } public string CategoryTitle { set; get; } public int ArticleID { set; get; } public string ArticleTitle { set; get; } public string URLArticleTitle { set; get; } public DateTime ArticleDate; public string ArticleContent { set; get; } } #3 (green box) - Displays last x articles. Uses the same ViewModel as brown box #2 #4 (blue box) - Displays list of upcoming events. Uses dataContext.Model.Event as ViewModel Boxes #1, #2 and #4 will repeat all over the site and they are part of Master Page. So, my question is: what is the best way to transfer this data from Model to Controller and finally to View pages? Should I make a controller for master page and ViewModel class that will wrap all this classes together OR Should I create partial Views for every of these boxes and make each of them inherit appropriate class (if it is even possible that it works this way?) OR Should I put this repeated code in all controllers and all additional data transfer via ViewData, which would be probably the worse way :) OR There is maybe a better and more simple way but I don't know/see it? Thanks in advance, Ile EDIT: If your answer is #1, then please explain how to make a controller for master page! EDIT 2: In this tutorial is described how to pass data to master page using abstract class: http://www.asp.net/LEARN/mvc/tutorial-13-cs.aspx In "Listing 5 – Controllers\MoviesController.cs", data is retrieved directly from database using LINQ, not from repository. So, I wonder if this is just in this tutorial, or there is some trick here and repository can't/shouldn't be used?

    Read the article

  • Custom HTML attributes on SelectListItems in MVC2?

    - by blesh
    I have a need to add custom HTML attributes, specifically classes or styles to option tags in the selects generated by Html.DropDownFor(). I've been playing with it, and for the life of me I can't figure out what I need to do to get what I need working. Assuming I have a list of colors that I'm generating the dropdown for, where the option value is the color's identifier, and the text is the name... here's what I'd like to be able to see as output: <select name="Color"> <option value="1" style="background:#ff0000">Red</option> <option value="2" style="background:#00ff00">Green</option> <option value="3" style="background:#0000ff">Blue</option> <!-- more here --> <option value="25" style="background:#f00f00">Foo Foo</option> </select

    Read the article

  • Making flexible C# code in MVC2 for Stored Procedures

    - by cc0
    Thanks to Darin Dimitrov's suggestion I got a big step further in understanding good MVC code, but I'm having some problems making it flexible. I implemented Darin's suggested solution, and it works perfectly for single controllers. However I'm having some trouble implementing it with some flexibility. What I'm looking for is this; To be able to make dynamic column names in json Instead of using "Column1: 'value', ..." and "Column2: 'value', ..." inside the json, I'd like to use for example "id: 'value', ..." and "place: 'value' ..." for one stored procedure, and "animal" and "type" in another (inside the json format). To be able to make dynamic amounts of columns dependent on which stored procedure is called Some stored procedures I'll want to read more than 2 rows from, is there a smart way of accomplishing that? To be able to make numeric (floats and integers) rows from the database be presented inside the json without quotes Like this (name and age); { Column1: "John", Column2: 53 }, I would be very grateful for any feedback and suggestions / code examples I can get here. Even imperfect ones.

    Read the article

  • MVC2 Checkbox problem...

    - by BitFiddler
    When I used the html Helper Checkbox, it produces 2 form elements. I understand why this is, and I have no problem with it except: The un-checking of the checkbox does not seem to be in sync with the 'hidden' value. What I mean is that when I have a bunch of checkboxes being generated in a loop: <%=Html.CheckBox("model.MarketCategories[" & i & "].Value", category.Value)%> and the user deselects and checkbox and the category.Value is FALSE, the code being generated is: <input checked="checked" id="model_MarketCategories_0__Value" name="model.MarketCategories[0].Value" type="checkbox" value="true" /> <input name="model.MarketCategories[0].Value" type="hidden" value="false" /> This is wrong since the Value is False the checkbox should NOT be checked. Any ideas why this is happening?

    Read the article

  • Return HTTP 404 when MVC2 view does not exist

    - by Dmitriy Nagirnyak
    Hi, I just need to have the a small CMS-like controller. The easiest way would be something like this: public class HomeController : Controller { public ActionResult View(string name) { if (!ViewExists(name)) return new HttpNotFoundResult(); return View(name); } private bool ViewExists(string name) { // How to check if the view exists without checking the file itself? } } The question is how to return HTTP 404 if the there is no view available? Probably I can check the files in appropriate locations and cache the result, but that feels really dirty. Thanks, Dmitriy.

    Read the article

  • asp.net mvc2 - controller for master page?

    - by ile
    I've just finished my first ASP.NET MVC (2) CMS. Next step is to build website that will show data from CMS's database. This is website design: #1 (Red box) - displays article categories. ViewModel: public class CategoriesDisplay { public CategoriesDisplay() { } public int CategoryID { set; get; } public string CategoryTitle { set; get; } } #2 (Brown box) - displays last x articles; skips those from green box #3. Viewmodel: public class ArticleDisplay { public ArticleDisplay() { } public int CategoryID { set; get; } public string CategoryTitle { set; get; } public int ArticleID { set; get; } public string ArticleTitle { set; get; } public string URLArticleTitle { set; get; } public DateTime ArticleDate; public string ArticleContent { set; get; } } #3 (green box) - Displays last x articles. Uses the same ViewModel as brown box #2 #4 (blue box) - Displays list of upcoming events. Uses dataContext.Model.Event as ViewModel Boxes #1, #2 and #4 will repeat all over the site and they are part of Master Page. So, my question is: what is the best way to transfer this data from Model to Controller and finally to View pages? Should I make a controller for master page and ViewModel class that will wrap all this classes together OR Should I create partial Views for every of these boxes and make each of them inherit appropriate class (if it is even possible that it works this way?) OR Should I put this repeated code in all controllers and all additional data transfer via ViewData, which would be probably the worse way :) OR There is maybe a better and more simple way but I don't know/see it? Thanks in advance, Ile

    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

  • JQuery validation without requiring MS scripts in asp.net mvc2 project

    - by Jim Geurts
    Is it possible to use the new client side validation features of asp.net MVC 2 without having to use the MS scripts (MicrosoftAjax.js, MicrosoftMvcAjax.js, MicrosoftMvcValidation.js)? I use JQuery throughout my application; JQuery has a great plugin for validation and I don't really want to force my users to load MS scripts just for validation. Is this possible? If so, any suggestions for how to accomplish it are appreciated.

    Read the article

  • Asp.net MVC2 Custom jquery validation: client -side

    - by Lullaby
    Hi. I want to create a validation rule for 2 date-pickers (startDate less then endDate). I create a validation attribute: [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public sealed class DateCompareAttribute : ValidationAttribute { private const string _defaultErrorMessage = "'{0}' is less then '{1}'."; public DateCompareAttribute(string startDateProperty, string endDateProperty) : base(_defaultErrorMessage) { StartDateProperty = startDateProperty; EndDateProperty = endDateProperty; } public string StartDateProperty { get; private set; } public string EndDateProperty { get; private set; } public override string FormatErrorMessage(string name) { return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, StartDateProperty, EndDateProperty); } public override bool IsValid(object value) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); object startValue = properties.Find(StartDateProperty, true).GetValue(value); object endValue = properties.Find(EndDateProperty, true).GetValue(value); if (startValue.GetType() == typeof(DateTime?) && endValue.GetType() == typeof(DateTime?)) { var start = ((DateTime?)startValue); var end = ((DateTime?)endValue); return (start.Value < end.Value); } return false; } } and added ti to my Dto: [DateCompare("StartDate", "EndDate")] public class QualificationInput{...} I created a validator: public class DateCompareValidator : DataAnnotationsModelValidator { string startField; private string endField; string _message; public DateCompareValidator(ModelMetadata metadata, ControllerContext context , DateCompareAttribute attribute) : base(metadata, context, attribute) { startField = attribute.StartDateProperty; endField = attribute.EndDateProperty; _message = attribute.ErrorMessage; } public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() { var rule = new ModelClientValidationRule { ErrorMessage = _message, ValidationType = "dateCompare" }; rule.ValidationParameters.Add("startField", startField); rule.ValidationParameters.Add("endField", endField); return new[] { rule }; } } And registered it in Global.asax.cs in Application_Start(): DataAnnotationsModelValidatorProvider .RegisterAdapter(typeof(DateCompareAttribute), typeof(DateCompareValidator)); In MicrosoftMvcJQueryValidation.js I have made this changes: switch (thisRule.ValidationType) { ..... case "dateCompare": __MVC_ApplyValidator_DateCompare(rulesObj, thisRule.ValidationParameters["startField"], thisRule.ValidationParameters["endField"]); break; ..... } .... function __MVC_ApplyValidator_DateCompare(object, startField, endField) { object["startField"] = startField; object["endField"] = endField; } jQuery.validator.addMethod("dateCompare", function(value, element, params) { if ($('#' + params["startField"]).val() < $('#' + params["endField"]).val()) { return true; } return false; }, jQuery.format("Error")); But it doesn't work :( no client side validation on this type of rule (the others type like required works fine) What I'm doing wrong?

    Read the article

  • MVC2 Ajax Form does unwanted page refresh

    - by Kay
    Hi, I am pretty new to MVC. I have my first Ajax Form here: <div id="test"></div> <div id="MainChatMenu"> <% using (Ajax.BeginForm("SendMessage", "MainChat", new AjaxOptions { UpdateTargetId="test"})) { %> <input id="chatMessageText" type="text" maxlength="200" /> <input type="submit" value="Go"/> <% } %> Now, if I click the submit button, the page is reloading, goint to mysite/controller/action. I thought that the default behaviour of the Ajax.BeginForm was exactly not to do that? Where's my newbie mistake? My Controller is called correctly, but data passing also doesn't work. Probably because of the same mistake? Here's the code: public class MainChatController : Controller { [AcceptVerbs(HttpVerbs.Post)] public EmptyResult SendMessage(FormCollection formValues) { return new EmptyResult(); } }

    Read the article

  • ASP.NET MVC2 JQuery datepicker errors

    - by Andy Evans
    I'm having the "Microsoft JScript runtime error: Object doesn't support this property or method" error when calling the datepicker function on a textbox generated from my data model. in the head section I have: <link href="../../Content/Site.css" rel="stylesheet" type="text/css" /> <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script> <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $('#dob').datepicker(); }); and in the body section I have: <% Html.EnableClientValidation(); %> <% using (Html.BeginForm()) { %> ... <tr> <td class="label">Date of Birth:</td> <td><%: Html.TextBoxFor(model => model.dob, new { @class = "inputtext" })%></td> <td><%: Html.ValidationMessageFor(model => model.dob) %></td> </tr> ... <% } %> Do I have something in the wrong place? Again, you folks are a great help and assistance would be greatly appreciated.

    Read the article

  • MVC2 Client validation with Annotations in View with RenderAction

    - by Olle
    I'm having problem with client side validation on a View that renders a dropdownlist with help of a Html.RenderAction. I have two controllers. SpecieController and CatchController and I've created ViewModels for my views. I want to keep it as DRY as possible and I will most probably need a DropDownList for all Specie elsewhere in the near future. When I create a Catch i need to set a relationship to one specie, I do this with an id that I get from the DropDownList of Species. ViewModels.Catch.Create [Required] public int Length { get; set; } [Required] public int Weight { get; set; } [Required] [Range(1, int.MaxValue)] public int SpecieId { get; set; } ViewModels.Specie.List public DropDownList(IEnumerable<SelectListItem> species) { this.Species = species; } public IEnumerable<SelectListItem> Species { get; private set; } My View for the Catch.Create action uses the ViewModels.Catch.Create as a model. But it feels that I'm missing something in the implemetation. What I want in my head is to connect the selected value in the DropDownList that comes from the RenderAction to my SpecieId. View.Catch.Create <div class="editor-label"> <%: Html.LabelFor(model => model.SpecieId) %> </div> <div class="editor-field"> <%-- Before DRY refactoring, works like I want but not DRY <%: Html.DropDownListFor(model => model.SpecieId, Model.Species) %> --%> <% Html.RenderAction("DropDownList", "Specie"); %> <%: Html.ValidationMessageFor(model => model.SpecieId) %> </div> CatchController.Create [HttpPost] public ActionResult Create(ViewModels.CatchModels.Create myCatch) { if (ModelState.IsValid) { // Can we make this StronglyTyped? int specieId = int.Parse(Request["Species"]); // Save to db Catch newCatch = new Catch(); newCatch.Length = myCatch.Length; newCatch.Weight = myCatch.Weight; newCatch.Specie = SpecieService.GetById(specieId); newCatch.User = UserService.GetUserByUsername(User.Identity.Name); CatchService.Save(newCatch); } This scenario works but not as smooth as i want. ClientSide validation does not work for SpecieId (after i refactored), I see why but don't know how I can ix it. Can I "glue" the DropDownList SelectedValue into myCatch so I don't need to get the value from Request["Species"] Thanks in advance for taking your time on this.

    Read the article

  • MVC2 Binding isn't working for Html.DropDownListFor<>

    - by devlife
    I'm trying to use the Html.DropDownListFor< HtmlHelper and am having a little trouble binding on post. The HTML renders properly but I never get a "selected" value when submitting. <%= Html.DropDownListFor( m => m.TimeZones, Model.TimeZones, new { @class = "SecureDropDown", name = "SelectedTimeZone" } ) %> [Bind(Exclude = "TimeZones")] public class SettingsViewModel : ProfileBaseModel { public IEnumerable TimeZones { get; set; } public string TimeZone { get; set; } public SettingsViewModel() { TimeZones = GetTimeZones(); TimeZone = string.Empty; } private static IEnumerable GetTimeZones() { var timeZones = TimeZoneInfo.GetSystemTimeZones().ToList(); return timeZones.Select( t = new SelectListItem { Text = t.DisplayName, Value = t.Id } ); } } I've tried a few different things and am sure I am doing something stupid... just not sure what it is :)

    Read the article

  • ASP MVC2 model binding issue on POST

    - by Brandon Linton
    So I'm looking at moving from MVC 1.0 to MVC 2.0 RTM. One of the conventions I'd like to start following is using the strongly-typed HTML helpers for generating controls like text boxes. However, it looks like it won't be an easy jump. I tried migrating my first form, replacing lines like this: <%= Html.TextBox("FirstName", Model.Data.FirstName, new {maxlength = 30}) %> ...for lines like this: <%= Html.TextBoxFor(x => x.Data.FirstName, new {maxlength = 30}) %> Previously, this would map into its appropriate view model on a POST, using the following method signature: [AcceptVerbs(HttpVerbs.Post)] public ActionResult Registration(AccountViewInfo viewInfo) Instead, it currently gets an empty object back. I believe the disconnect is in the fact that we pass the view model into a larger aggregate object that has some page metadata and other fun stuff along with it (hence x.Data.FirstName instead of x.FirstName). So my question is: what is the best way to use the strongly-typed helpers while still allowing the MVC framework to appropriately cast the form collection to my view-model as it does in the original line? Is there any way to do it without changing the aggregate type we pass to the view? Thanks!

    Read the article

  • MVC2 Controller is passed a null object as a parameter

    - by Steve Wright
    I am having an issue with a controller getting a null object as a parameter: [HttpGet] public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(LoginViewData userLogin) { Assert.IsNotNull(userLogin); // FAILS if (ModelState.IsValid) { } return View(userLogin); } The LoginViewData is being passed as null when the HttpPost is called: Using MvcContrib.FluentHtml: <h2>Login to your Account</h2> <div id="contact" class="rounded-10"> <%using (Html.BeginForm()) { %> <fieldset> <ol> <li> <%= this.TextBox(f=>f.UserLogin).Label("Name: ", "name") %> <%= Html.ValidationMessageFor(m => m.UserLogin) %> </li> <li> <%= this.Password(u => u.UserPassword).Label("Password:", "name") %> <%= Html.ValidationMessageFor(m => m.UserPassword) %> </li> <li> <%= this.CheckBox(f => f.RememberMe).LabelAfter("Remember Me")%> </li> <li> <label for="submit" class="name">&nbsp;</label> <%= this.SubmitButton("Login")%> </li> </ol> </fieldset> <% } %> <p>If you forgot your user name or password, please use the Password Retrieval Form.</p> </div> The view inherits from MvcContrib.FluentHtml.ModelViewPage and is strongly typed against the LoginViewData object: public class LoginViewData { [Required] [DisplayName("User Login")] public string UserLogin { get; set; } [Required] [DisplayName("Password")] public string UserPassword { get; set; } [DisplayName("Remember Me?")] public bool RememberMe { get; set; } } Any ideas on why this would be happening? UPDATE I rebuilt the web project from scratch and that fixed it. I am still concerned why it happened.

    Read the article

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