Search Results

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

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

  • Problems deploying MVC2 - Could not load type 'System.Web.Mvc.UrlParameter'

    - by Evgeny
    Hi Everyone, I have problems deploying MVC2 application to my hosting. It shows the following error: Could not load type 'System.Web.Mvc.UrlParameter' from assembly 'System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. It looks like it does not understand the new "optional URL parameters" feature of MVC2. This is just a simple test application I created with "New Project" wizard in VWD 2008. It works ok localy both in IIS and Visual Studio web servers. MVC1 web sites are working ok on the hosting server. I've contacted the hosting support and they installed MVC2 but the problem still exists. The web site is working in ASP.NET 2.0 integrated pipeline mode. Does anyone know why it is happening? Thank you!

    Read the article

  • Cannot debug views in MVC2 project, getting "The resource cannot be found" error

    - by schefdev
    I'm running Visual Studio 2008 sp1 on Win7, with MVC2 RTM installed. I created a new MVC2 project using the wizard and am unable to debug specific pages. With webforms and even MVC1, I was able to sit on a View page, hit F5, and then have the integrated web server in VS2008 start on the page I was working on. Very handy for building up app logic. When I try this now I get a "The resource cannot be found" error page. I retried this just now with a stock new MVC2 Web Application project. Here are the steps I took after creating the new project to reproduce: Open up project settings. Under the Web subtab, set the Start Action to "Current Page". Leave all the other settings as is. Open one of the views up (e.g. Account/Register.aspx) Hit F5 to debug the project Note that the browser window which displays shows the error message "The resource cannot be found". The link I saw in my browser for this run was: http://localhost:49471/Views/Account/Register.aspx I did some googling and found suggestions related to ensuring all HTTP server pieces were installed. I double checked and made sure that "HTTP Errors" and "HTTP Redirection" were both installed. If I leave the project setting as it was originally, set to "Specific Page" with nothing in the text box, then routing works and I always get the default home page. I'm hoping this isn't the only option. Thanks!

    Read the article

  • MVC2 DataAnnotations validation with inheritance

    - by bhiku
    Hi, I have a .NET 2.0 class the properties of which are marked virtual.I need to use the class as a model in a MVC2 application. So, I have created a .NET 3.5 class inheriting from the .NET 2.0 class and added the DataAnnotations attributes to the overriden properties in the new class. A snippet of what I have done is below // .NET 2.0 class public class Customer { private string _firstName = ""; public virtual string FirstName { get { return _firstName; } set { _firstName = value; } } } // .NET 3.5 class public class MVCCustomer : Customer { [Required(ErrorMessage="Firstname is required")] public override string FirstName { get { return base.FirstName; } set { base.FirstName = value; } } } I have used the class as the model for a MVC2 view using the HtmlFor helpers. Serverside validation works correctly but the client side validation does not. Specifically the validation error is not displayed on the page. What am I missing, or is it only possible to do this using buddy classes. Thanks.

    Read the article

  • JqGrid don't work in ASP .NET MVC2

    - by Raouf
    I have a project in ASP.NET MVC1 using VB.NET controlers and JqGrid. it works fine under MVC1. After migrating the project to ASP.NET MVC2, the grid is no longer populated. It seems that there is some new restrictions on returned Jsonresult in MVC2. How to solve this in VB.NET. Controler function populating the jqgrid is something like this : Function GetGridRecordset(ByVal qry As String) As JsonResult Dim result = New JsonResult() ... ... Return result End Function Is there anyone who have a solution? Thank you very much!

    Read the article

  • JqGrid doesn't work in ASP.NET MVC2

    - by Raouf
    I have a project in ASP.NET MVC1 using VB.NET controlers and JqGrid. it works fine under MVC1. After migrating the project to ASP.NET MVC2, the grid is no longer populated. It seems that there is some new restrictions on returned Jsonresult in MVC2. How to solve this in VB.NET. Controler function populating the jqgrid is something like this : Function GetGridRecordset(ByVal qry As String) As JsonResult Dim result = New JsonResult() ... ... Return result End Function Is there anyone who have a solution?

    Read the article

  • A realistic and usable (VS2010) MVC2 project template?

    - by pomarc
    Hello. everybody. The default MVC2 web project template which VS2010 creates when you select "ASP.NET MVC2 Web Application" is quite a nice start... but nowhere near a realistic app framework. E.G.: user accounts without such features as password recover easily customizabile (and maybe multilingual) error messages an interface to manage users, such a searcheable user list, user edit and so on which an admin can use and these are just the beginning of the usual, mandatory basic features a web site of any size may use. Searching through the online projects templates doesn't seem to help, ehiter. Are there any project template sites or else that you are aware of, that gives such features? thanks a lot!

    Read the article

  • Struggling running ASP MVC2 on IIS6.0

    - by Luke
    Hi I could use a little Help using MVC2 on an IIS6.0 Its an MVC2 RC2 [.NET 3.5]. I followed the famous Haacked Tutorial, created a virtual folder, created a Default.aspx Website for my Project, put everything to my virtual folder. The routing is modified, using wildcard mapping [anyway its not running without, too], according to the Tutorial. I also checked, that all Webservices are running [asp.net 2 / asp.net 4 / active server pages]. The routing is working fine on my development machine, even checked it using Haacks routing debugger ... [http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx] Seems fine so far, but I get only 404 - not found errors. Is there something I might be missing ? Global.asax.cs public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", "{controller}.mvc/{action}/{id}", new { action = "Index", id = "" } ); routes.MapRoute( "Root", "", new { controller = "Home", action = "Index", id = "" } ); } Default.aspx.cs public void Page_Load(object sender, System.EventArgs e) { // Change the current path so that the Routing handler can correctly interpret // the request, then restore the original path so that the OutputCache module // can correctly process the response (if caching is enabled). string originalPath = Request.Path; HttpContext.Current.RewritePath(Request.ApplicationPath, false); IHttpHandler httpHandler = new MvcHttpHandler(); httpHandler.ProcessRequest(HttpContext.Current); HttpContext.Current.RewritePath(originalPath, false); }

    Read the article

  • Broken RenderPartial After Upgrade To ASP.NET MVC2

    - by mxmissile
    I upgraded a MVC1 project to MVC2, now all my calls to RenderPartial are throwing System.ArgumentNullException: Value cannot be null. However this does works: <% Html.RenderPartial("~/Views/Shared/LogOnUserControl.ascx"); %> And this does not (works in MVC1): <% Html.RenderPartial("LogOnUserControl"); %> Did the behavior of RenderPartial change?

    Read the article

  • ASP.NET 4.0 MVC2 routing on IIS 6

    - by Kim Rossey
    ASP.NET 4.0 MVC2 routing on IIS 6 is not working for me with all the methods used for 3.5 Works fine as long as I build in 3.5 but building in 4.0 and setting the server to use 4.0 I loose my routing. Anyone seen this and been able to resolve it?

    Read the article

  • Need to change the default browser for an MVC2 project

    - by schefdev
    I just created my first MVC2 project using the standard template. I need to be able to change the default browser for my project to test in IE (I use chrome as the default on my OS). Unfortunately, the "right click on default.aspx" suggestion which worked in MVC1 can't work with these new projects as they don't have that file. I'm sure I'm overlooking something simple... Thanks.

    Read the article

  • TempData Error in ASP .NET MVC2

    - by Mauro
    Hi, I'm looking for a description of the reasons why this error is generated and what are the possible fixes to it. In my ASP.NET MVC2 controller I just added a TempData data passing. Server Error in '/' Application. The SessionStateTempDataProvider class requires session state to be enabled. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: The SessionStateTempDataProvider class requires session state to be enabled.

    Read the article

  • MVC2: Best Way to Intercept ViewRequest and Alter ActionResult

    - by Matthew
    I'm building an ASP.NET MVC2 Web Application that requires some sophisticated authentication and business logic that cannot be achieved using the out of the box forms authentication. I'm new to MVC so bear with me... My plan was to mark all restricted View methods with one or more custom attributes (that contain additional data). The controller would then override the OnActionExecuting method to intercept requests, analyze the target view's attributes, and do a variety of different things, including re-routing the user to different places. I have the interception and attribute analysis working, but the redirection is not working as expected. I have tried setting the ActionExecutingContext.Result to null and even have tried spooling up controllers via reflection and invoking their action methods. No dice. I was able to achieve it this way... protected override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.HttpContext.Response.Redirect("/MyView", false); base.OnActionExecuting(filterContext); } This seems like a hack, and there has to be a better way...

    Read the article

  • Html.DropDownListFor<> and complex object in ASP.NET MVC2

    - by dagda1
    Hi, I am looking at ASP.NET MVC2 and trying to post a complex object using the new EditorFor syntax. I have a FraudDto object that has a FraudCategory child object and I want to set this object from the values that are posted from the form. Posting a simple object is not a problem but I am struggling with how to handle complex objects with child objects. I have the following parent FraudDto object whcih I am binding to on the form: public class FraudDto { public FraudCategoryDto FraudCategory { get; set; } public List<FraudCategoryDto> FraudCategories { get; private set; } public IEnumerable<SelectListItem> FraudCategoryList { get { return FraudCategories.Select(t => new SelectListItem { Text = t.Name, Value = t.Id.ToString() }); } The child FraudCategoryDto object looks like this: public class FraudCategoryDto { public int Id { get; set; } public string Name { get; set; } } On the form, I have the following code where I want to bind the FraudCategoryDto to the dropdown. The view is of type ViewPage: <td class="tac"> <strong>Category:</strong> </td> <td> <%= Html.DropDownListFor(x => x.FraudCategory, Model.FraudTypeList)%> </td> I then have the following controller code: [HttpPost] public virtual ViewResult SaveOrUpdate(FraudDto fraudDto) { return View(fraudDto); } When the form is posted to the server, the FraudCategory property of the Fraud object is null. Are there any additional steps I need to hook up this complex object? Cheers Paul

    Read the article

  • Using LINQ to SQL in ASP.NET MVC2 project

    - 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 appropriate 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

  • How to change ErrorMessage property of the DataAnnotation validation in MVC2.0

    - by Raj Aththanayake
    My task is to change the ErrorMessage property of the DataAnnotation validation attribute in MVC2.0. For example I should be able to pass an ID instead of the actual error message for the Model property and use that ID to retrieve some content(error message) from a another service e.g database, and display that error message in the View instead of the ID. In order to do this I need to set the DataAnnotation validation attribute’s ErrorMessage property. [StringLength(2, ErrorMessage = "EmailContentID.")] [DataType(DataType.EmailAddress)] public string Email { get; set; } It seems like an easy task by just overriding the DataAnnotationsModelValidatorProvider ‘s protected override IEnumerable GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable attributes) However it seems to be a complicated enough. a. MVC DatannotationsModelValidator’s ErrorMessage property is read only. So I cannot set anything here b. System.ComponentModel.DataAnnotationErrorMessage property(get and set) which is already set in MVC DatannotationsModelValidator so we cannot set again. If you try to set you get “The property cannot set more than once…” error message appears. public class CustomDataAnnotationProvider : DataAnnotationsModelValidatorProvider { protected override IEnumerable GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable attributes) { IEnumerable validators = base.GetValidators(metadata, context, attributes); foreach (ValidationAttribute validator in validators.OfType<ValidationAttribute>()) { validator.ErrorMessage = "Error string from DB"; } //...... } Can anyone please help me on this?

    Read the article

  • ASP.NET MVC2 Implementing Custom RoleManager problem

    - by ile
    To create a custom membership provider I followed these instructions: http://stackoverflow.com/questions/2771094/asp-net-mvc2-custom-membership and these: http://mattwrock.com/post/2009/10/14/Implementing-custom-Membership-Provider-and-Role-Provider-for-Authinticating-ASPNET-MVC-Applications.aspx So far, I've managed to implement custom membership provider and that part works fine. RoleManager still needs some modifications... Project structure: SAMembershipProvider.cs: public class SAMembershipProvider : MembershipProvider { #region - Properties - private int NewPasswordLength { get; set; } private string ConnectionString { get; set; } public bool enablePasswordReset { get; set; } public bool enablePasswordRetrieval { get; set; } public bool requiresQuestionAndAnswer { get; set; } public bool requiresUniqueEmail { get; set; } public int maxInvalidPasswordAttempts { get; set; } public int passwordAttemptWindow { get; set; } public MembershipPasswordFormat passwordFormat { get; set; } public int minRequiredNonAlphanumericCharacters { get; set; } public int minRequiredPasswordLength { get; set; } public string passwordStrengthRegularExpression { get; set; } public override string ApplicationName { get; set; } public override bool EnablePasswordRetrieval { get { return enablePasswordRetrieval; } } public override bool EnablePasswordReset { get { return enablePasswordReset; } } public override bool RequiresQuestionAndAnswer { get { return requiresQuestionAndAnswer; } } public override int MaxInvalidPasswordAttempts { get { return maxInvalidPasswordAttempts; } } public override int PasswordAttemptWindow { get { return passwordAttemptWindow; } } public override bool RequiresUniqueEmail { get { return requiresUniqueEmail; } } public override MembershipPasswordFormat PasswordFormat { get { return passwordFormat; } } public override int MinRequiredPasswordLength { get { return minRequiredPasswordLength; } } public override int MinRequiredNonAlphanumericCharacters { get { return minRequiredNonAlphanumericCharacters; } } public override string PasswordStrengthRegularExpression { get { return passwordStrengthRegularExpression; } } #endregion #region - Methods - public override void Initialize(string name, NameValueCollection config) { throw new NotImplementedException(); } public override bool ChangePassword(string username, string oldPassword, string newPassword) { throw new NotImplementedException(); } public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { throw new NotImplementedException(); } public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { throw new NotImplementedException(); } public override bool DeleteUser(string username, bool deleteAllRelatedData) { throw new NotImplementedException(); } public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override int GetNumberOfUsersOnline() { throw new NotImplementedException(); } public override string GetPassword(string username, string answer) { throw new NotImplementedException(); } public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { throw new NotImplementedException(); } public override MembershipUser GetUser(string username, bool userIsOnline) { throw new NotImplementedException(); } public override string GetUserNameByEmail(string email) { throw new NotImplementedException(); } protected override void OnValidatingPassword(ValidatePasswordEventArgs e) { base.OnValidatingPassword(e); } public override string ResetPassword(string username, string answer) { throw new NotImplementedException(); } public override bool UnlockUser(string userName) { throw new NotImplementedException(); } public override void UpdateUser(MembershipUser user) { throw new NotImplementedException(); } public override bool ValidateUser(string username, string password) { AccountRepository accountRepository = new AccountRepository(); var user = accountRepository.GetUser(username); if (string.IsNullOrEmpty(password.Trim())) return false; if (user == null) return false; //string hash = EncryptPassword(password); var email = user.Email; var pass = user.Password; if (user == null) return false; if (pass == password) { //User = user; return true; } return false; } #endregion protected string EncryptPassword(string password) { //we use codepage 1252 because that is what sql server uses byte[] pwdBytes = Encoding.GetEncoding(1252).GetBytes(password); byte[] hashBytes = System.Security.Cryptography.MD5.Create().ComputeHash(pwdBytes); return Encoding.GetEncoding(1252).GetString(hashBytes); } } SARoleProvider.cs public class SARoleProvider : RoleProvider { AccountRepository accountRepository = new AccountRepository(); public override bool IsUserInRole(string username, string roleName) { return true; } public override string ApplicationName { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override void AddUsersToRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override void CreateRole(string roleName) { throw new NotImplementedException(); } public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { throw new NotImplementedException(); } public override bool RoleExists(string roleName) { throw new NotImplementedException(); } public override string[] GetRolesForUser(string username) { int rolesCount = 0; IQueryable<RoleViewModel> rolesNames; try { // get roles for this user from DB... rolesNames = accountRepository.GetRolesForUser(username); rolesCount = rolesNames.Count(); } catch (Exception ex) { throw ex; } string[] roles = new string[rolesCount]; int counter = 0; foreach (var item in rolesNames) { roles[counter] = item.RoleName.ToString(); counter++; } return roles; } public override string[] GetUsersInRole(string roleName) { throw new NotImplementedException(); } public override string[] FindUsersInRole(string roleName, string usernameToMatch) { throw new NotImplementedException(); } public override string[] GetAllRoles() { throw new NotImplementedException(); } } AccountRepository.cs public class RoleViewModel { public string RoleName { get; set; } } public class AccountRepository { private DB db = new DB(); public User GetUser(string email) { return db.Users.SingleOrDefault(d => d.Email == email); } public IQueryable<RoleViewModel> GetRolesForUser(string email) { var result = ( from role in db.Roles join user in db.Users on role.RoleID equals user.RoleID where user.Email == email select new RoleViewModel { RoleName = role.Name }); return result; } } webconfig <membership defaultProvider="SAMembershipProvider" userIsOnlineTimeWindow="15"> <providers> <clear/> <add name="SAMembershipProvider" type="SA_Contacts.Membership.SAMembershipProvider, SA_Contacts" connectionStringName ="ShinyAntConnectionString" /> </providers> </membership> <roleManager defaultProvider="SARoleProvider" enabled="true" cacheRolesInCookie="true"> <providers> <clear/> <add name="SARoleProvider" type="SA_Contacts.Membership.SARoleProvider" connectionStringName ="ShinyAntConnectionString" /> </providers> </roleManager> AccountController.cs: public class AccountController : Controller { SAMembershipProvider provider = new SAMembershipProvider(); AccountRepository accountRepository = new AccountRepository(); public AccountController() { } public ActionResult LogOn() { return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult LogOn(string userName, string password, string returnUrl) { if (!ValidateLogOn(userName, password)) { return View(); } var user = accountRepository.GetUser(userName); var userFullName = user.FirstName + " " + user.LastName; FormsAuthentication.SetAuthCookie(userFullName, false); if (!String.IsNullOrEmpty(returnUrl) && returnUrl != "/") { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } public ActionResult LogOff() { FormsAuthentication.SignOut(); return RedirectToAction("Index", "Home"); } private bool ValidateLogOn(string userName, string password) { if (String.IsNullOrEmpty(userName)) { ModelState.AddModelError("username", "You must specify a username."); } if (String.IsNullOrEmpty(password)) { ModelState.AddModelError("password", "You must specify a password."); } if (!provider.ValidateUser(userName, password)) { ModelState.AddModelError("_FORM", "The username or password provided is incorrect."); } return ModelState.IsValid; } } In some testing controller I have following: [Authorize] public class ContactsController : Controller { SAMembershipProvider saMembershipProvider = new SAMembershipProvider(); SARoleProvider saRoleProvider = new SARoleProvider(); // // GET: /Contact/ public ActionResult Index() { string[] roleNames = Roles.GetRolesForUser("[email protected]"); // Outputs admin ViewData["r1"] = roleNames[0].ToString(); // Outputs True // I'm not even sure if this method is the same as the one below ViewData["r2"] = Roles.IsUserInRole("[email protected]", roleNames[0].ToString()); // Outputs True ViewData["r3"] = saRoleProvider.IsUserInRole("[email protected]", "admin"); return View(); } If I use attribute [Authorize] then everything works ok, but if I use [Authorize(Roles="admin")] then user is always rejected, like he is not in role. Any idea of what could be wrong here? Thanks in advance, Ile

    Read the article

  • MVC2 MSchart with detail grid

    - by ben
    Hello, I need the capability to display a chart, click on a region and display the details in a jqgrid on the same page. I tried using a pie Chart and I can't seem to capture or create a click event for the chart. The data points contain a .url property which I can redirect to a different page but I need to display details on the same page like a master-detail page.

    Read the article

  • custom MVC2 editortemplates

    - by tschreck
    i would like to create a library of custom EditorTemplates and DisplayTemplates. How do I "load" these into my MVC application? I want to be able to re-use my custom template library across a variety of MVC apps.

    Read the article

  • MVC2 Areas and unit testing for routes

    - by Alexander Shapovalov
    Hello, I want to test my routes in unit tests. But Areas is not working in my unit tests. Is it possible to test ASP.NET MVC 2 routes for Areas? I am using this code [SetUp] public void SetUp() { this.routes = new RouteCollection(); MvcApplication.RegisterRoutes(this.routes); } #endregion private RouteCollection routes; [Test] public void Should_Navigate_To_AdminUser_Controller_EditUser_Method() { HttpContextBase fackeCtx = CreateFackeContext("~/Admin/User/Edit/3"); RouteData routeData = this.routes.GetRouteData(fackeCtx); Assert.IsNotNull(routeData, "Route is not defined!"); Assert.AreEqual("Edit", routeData.Values["action"]); Assert.AreEqual("User", routeData.Values["controller"]); Assert.AreEqual("3", routeData.Values["id"]); }

    Read the article

  • Display custom error page when file upload exceeds allowed size in ASP.NET MVC2

    - by Marcus
    Hello! My main issue is that I want to display an custom error page when an uploaded file exceeds allowed size (maxRequestLength in web.config). When the big file is uploaded an HttpException is thrown before my upload action method in the controller is invoked. This is expected. I have tried to catch the exception in a custom attribute and also to override OnException in the controller. Why isnt it possible to catch the exception in either the attribute or the OnException method? Its possible though to catch the exception in Application_Error in global.asax but neither Response.Redirect nor Server.Transfer works for redirecting to the custom error page. Server.Transfer gives the "failed to process child request" error and response.redirect gives the "Http headers already sent" error. Any ideas? Thanks in advance! Marcus

    Read the article

  • Correct way to edit and update complex viewmodel objects using asp.net-mvc2 and entity framework

    - by jslatts
    I have a table in my database with a one to many relationship to another table: ParentObject ID Name Description ChildObject ID Name Description ParentObjectID AnotherObjectID The objects are mapped into Entity Framework and exposed through a data access class. It seemed like ViewModels are recommended when the data to be displayed greatly differs from the domain object, so I created a ViewModel as follows: public class ViewModel { public IList<ParentObject> ParentObjects { get; set; } public ParentObject selectedObject { get; set; } public IList<ChildObject> ChildObjects { get; set; } } I have a view that displays a list of ParentObjects and when clicked will allow a ChildObject to be modified saved. <% using (Html.BeginForm()) { %> <table> <% foreach (var parent in Model.ParentObjects) { %> <tr> <td> ObjectID [<%= Html.Encode(parent.ID)%>] </td> <td> <%= Html.Encode(parent.Name)%> </td> <td> <%= Html.Encode(parent.Description)%> </td> </tr> <% } %> </table> <% if (Model.ParentObject != null) { %> <div> Name:<br /> <%= Html.TextBoxFor(model => model.ParentObject.Name) %> <%= Html.ValidationMessageFor(model => model.ParentObject.Name, "*")%> </div> <div> Description:<br /> <%= Html.TextBoxFor(model => model.ParentObject.Description) %> <%= Html.ValidationMessageFor(model => model.ParentObject.Description, "*")%> </div> <div> Child Objects </div> <% for (int i = 0; i < Model.ParentObject.ChildObjects.Count(); i++) { %> <div> <%= Html.DisplayTextFor(sd => sd.ChildObjects[i].Name) %> </div> <div> <%= Html.HiddenFor(sd => sd.ChildObjects[i].ID )%> <%= Html.TextBoxFor( sd => sd.ChildObjects[i].Description) %> <%= Html.ValidationMessageFor(sd => sd.ChildObjects[i].Description, "*") %> </div> <% } } } %> This all works fine. My question is around the best way to update the EF objects and persist the changes back to the database. I initially tried: [HttpPost] public ActionResult Edit(ViewModel viewModel) { ParentObject parent = myRepository.GetParentObjectByID(viewModel.SelectedObject.ID); if ((!ModelState.IsValid) || !TryUpdateModel(parent, "SelectedObject", new[] { "Name", "Description" })) { || !TryUpdateModel(parent.ChildObjects, "ChildObjects", new[] { "Name", "Description" })) { //Code to handle failure and return the current model snipped return View(viewModel); } myRepository.Save(); return RedirectToAction("Edit"); } When I try to save a change to the child object, I get this exception: Entities in 'MyEntities.ChildObject' participate in the 'FK_ChildObject_AnotherObject' relationship. 0 related 'AnotherObject' were found. 1 'AnotherObject' is expected. Investigation on StackOverflow and generally googling led me to this blog post that seems to describe my problem: TryUpdateModel() does not correctly handle nested collections. Apparently, (and stepping through the debugger confirms this) it creates a new ChildObject instead of associating with the EF objects from my instantiated context. My hacky work around is this: if (viewModel.ChildObjects.Count > 0) { foreach (ChildObject modelChildObject in viewModel.ChildObjects) { ChildObject childToUpdate = ParentObject.ChildObject.Where(a => a.ID == modelChildObject.ID).First(); childToUpdate.Name = modelChildObject.Name; } } This seems to work fine. My question to you good folks: Is there correct way to do this? I tried following the suggestion for making a custom model binder per the blog link I posted above but it didn't work (there was an issue with reflection) and I needed to get something going ASAP. PS - I tried to cleanup the code to hide specific information, so beware I may have hosed something up. I mainly just want to know if other people have solved this problem. Thanks!

    Read the article

  • asp.net mvc2 ajax.actionlink is not working refresh problem

    - by mazhar kaunain baig
    has someone make ajax.actionlink for delete to work properly.After deleting the record successfully at the end it is not refreshing the page properly. the page refresh is my problem. i have defined the updatetarget id and returning view(model) from my controller but it is returning the master page with it. So the thing is that i am having a page with a page.I have used redirect as well which is not refreshing, <%= Ajax.ActionLink("Delete", "Delete", new { id = item.int_OrganizationGroupId }, new AjaxOptions { UpdateTargetId = "abc", HttpMethod = "Post", Confirm = "Delete Group with Organization Group ID:" + item.int_OrganizationGroupId + " Organization Group Name:" + item.vcr_OrganizationGroupName, OnSuccess = "handleSuccess" })%>| abc is the id of the table From controller View("ManageGroup,Model);

    Read the article

  • Using jQuery for client side validation in MVC2 RTM

    - by tigermain
    Scott Gu's tutorial on Model validation gets us all set up with the MS client side validation using the following scripts: <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script> <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script> However I've seen various posts allowing us to utilise jQuery instead with the following code: <script src="https://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script> <script src="https://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js" type="text/javascript"></script> <script src="<%= Url.Content("~/scripts/MicrosoftMvcJQueryValidation.js") %>" type="text/javascript"></script> However MicrosoftMvcJQueryValidation.js does not ship with the solution and from what I read it should be part of the Futures pack which is no longer available on CodePlex. I managed to find a version alongside jQuery 1.3.2 but it does not work. What is the forward going solution!?

    Read the article

  • Modelbinding Failing VS2010 asp.net mvc2

    - by Rob Ellis
    The contactAddModel.Search always comes through as null - any ideas? View declaration <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<rs30UserWeb.Models.StatusIndexModel>" %> ViewModels public class StatusIndexModel { public ContactAddModel contactAddModel; public StatusMessageModel statusMessageModel; } public class ContactAddModel { [Required(ErrorMessage="Contact search string")] [DisplayName("Contact Search")] public string Search { get; set; } } View content <% using (Html.BeginForm("AddContact", "Status")) { %> <div> <fieldset> <legend>Add a new Contact</legend> <div class="editor-label"> <%= Html.LabelFor(m => m.contactAddModel.Search) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(m => m.contactAddModel.Search)%> <%= Html.ValidationMessageFor(m => m.contactAddModel.Search)%> </div> <p> <input type="submit" value="Add Contact" /> </p> </fieldset> </div> <% } %> Controller [HttpPost] public ActionResult AddContact(Models.ContactAddModel model) { if (u != null) { } else { ModelState.AddModelError("contactAddModel.Search", "User not found"); } return View("Index"); }

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >