UpdatePersonalDetails( PersonalDetailsViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) { return; } var user = GetCurrentUser(); user.UserDetails.Title = model.Title; user.UserDetails.FirstName = model.FirstName; user.UserDetails.LastName = model.LastName; user.UserDetails.Gender = model.Gender; user.UserDetails.DateOfBirth = model.DateOfBirth; var result = _userManager.Update(user); if (result.Succeeded) { RedirectToManager(ManageMessageId.UserDetailsUpdateSuccess); return; } AddErrors(result, context); }
SendTwoFactorCode( SendTwoFactorCodeViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) { return; } var userId = GetVerifiedUserId(); var user = _userManager.FindById(userId); if (user != null) { var code = _userManager.GenerateTwoFactorToken( user.Id, model.Provider); _userManager.NotifyTwoFactorToken(userId, model.Provider, code); StateController.Navigate( "VerifyTwoFactorCode", new NavigationData { { ProviderNameKey, model.Provider }, { CodeKey, code }, { ReturnUrlKey, StateContext.Bag.ReturnUrl } }); } else { context.ModelState.AddModelError( "", "Unable to identify current user!"); } }
AddPhoneNumber( AddPhoneNumberViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) { return; } var userId = _context.User.Identity.GetUserId(); var code = _userManager.GenerateChangePhoneNumberToken( userId, model.PhoneNumber); if (_userManager.SmsService != null) { var message = new IdentityMessage { Destination = model.PhoneNumber, Body = SmsService.CreateAuthenticatePhoneMessage(code) }; Task.Run( async() => { await _userManager.SmsService.SendAsync(message); }); } // Modify this code to remove security code reference for // production - the code value should only be included for // demonstration purposes! StateController.Navigate( "VerifyPhoneNumber", new NavigationData { { "PhoneNumber", model.PhoneNumber }, { "DemoCode", code } }); }
VerifyTwoFactorCode( VerifyTwoFactorCodeViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) { return; } var result = TwoFactorSignIn( model.Provider, model.Code, isPersistent: false, rememberBrowser: model.RememberBrowser); switch (result) { case SignInStatus.Success: RedirectToLocal(); return; case SignInStatus.LockedOut: StateController.Navigate("AccountLocked"); return; default: context.ModelState.AddModelError("Code", "Invalid Code"); break; } }
ResetPassword(ResetPasswordViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) { return; } string code = StateContext.Data[CodeKey] as string; if (code == null) { context.ModelState.AddModelError("", "Invalid call to this page"); return; } var user = _userManager.FindByEmail(model.Email); if (user == null) { context.ModelState.AddModelError("", "User not found!"); return; } var result = _userManager.ResetPassword(user.Id, code, model.Password); if (result.Succeeded) { StateController.Navigate("ResetPasswordConfirmation"); } }
private static void AddErrors(IdentityResult result, ModelMethodContext context) { foreach (var error in result.Errors) { context.ModelState.AddModelError("", error); } }
VerifyPhoneNumber( VerifyPhoneNumberViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) { return; } var userId = _context.User.Identity.GetUserId(); var result = _userManager.ChangePhoneNumber( userId, model.PhoneNumber, model.Code); if (result.Succeeded) { var user = _userManager.FindById(userId); if (user != null) { SignIn(user, false); RedirectToManager(ManageMessageId.AddPhoneSuccess); } } else { context.ModelState.AddModelError("", "Invalid verification code"); } }
public void AddPhoneNumber( AddPhoneNumberViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) return; var userId = _context.User.Identity.GetUserId(); var code = _userManager.GenerateChangePhoneNumberToken( userId, model.PhoneNumber); if (_userManager.SmsService != null) { var message = new IdentityMessage { Destination = model.PhoneNumber, Body = SmsService.CreateAuthenticatePhoneMessage(code) }; Task.Run( async () => { await _userManager.SmsService.SendAsync(message); }); } // Modify this code to remove security code reference for // production - the code value should only be included for // demonstration purposes! StateController.Navigate( "VerifyPhoneNumber", new NavigationData { {"PhoneNumber", model.PhoneNumber}, {"DemoCode", code} }); }
AddErrors(IdentityResult result, ModelMethodContext context) { foreach (var error in result.Errors) { context.ModelState.AddModelError("", error); } }
// The id parameter name should match the DataKeyNames value set on the control public void UpdateTrain(int StaticTrainId, ModelMethodContext context) { StaticTrain item = db.StaticTrains.Find(StaticTrainId); if (item == null) { context.ModelState.AddModelError("", $"Item with id {StaticTrainId} was not found."); return; } try { context.TryUpdateModel(item); } catch (ArgumentOutOfRangeException e) { if (e.ParamName == "Departure") { context.ModelState.AddModelError("", $"The value entered for the Departure field is not valid. {e.Message}"); } } ValidateTrain(item); if (context.ModelState.IsValid) { db.SaveChanges(); } }
public void UpdateProduct(string ProductID, ModelMethodContext ctx) { Product item = GetProductById(ProductID); if (item == null) { ctx.ModelState.AddModelError("", $"Item with id {ProductID} was not found"); return; } if (ctx.ModelState.IsValid) { try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { HandleConcurrencyError(ex, ctx, IsEdit: true); } catch (DbEntityValidationException ex) { HandleValidationError(ex, ctx); } catch (Exception ex) { HandleError(ex, ctx); } } }
public void InsertProduct(ModelMethodContext cxt) { var item = new Product(); cxt.TryUpdateModel(item); if (cxt.ModelState.IsValid) { db.Products.Add(item); try { db.SaveChanges(); } catch (DbEntityValidationException ex) { HandleValidationError(ex, cxt); } catch (Exception ex) { HandleError(ex, cxt); } } }
public void InsertStudent(ModelMethodContext context) { var item = new Student(); context.TryUpdateModel(item); if (context.ModelState.IsValid) { db.Students.Add(item); db.SaveChanges(); } }
private void HandleValidationError(DbEntityValidationException ex, ModelMethodContext cxt) { foreach (var ve in ex.EntityValidationErrors) { foreach (var e in ve.ValidationErrors) { cxt.ModelState.AddModelError("", $"Error: {e.ErrorMessage}"); } } }
public void InsertarAlumno(ModelMethodContext mmc) { using (bd_notasAlumnosContexto bd = new bd_notasAlumnosContexto()) { var objAlumno = new alumno(); mmc.TryUpdateModel(objAlumno); if (mmc.ModelState.IsValid) { // Guardar los cambios bd.alumnos.Add(objAlumno); bd.SaveChanges(); } } }
private void HandleConcurrencyError(DbUpdateConcurrencyException ex, ModelMethodContext cxt, bool IsEdit) { ex.Entries.Single().Reload(); if (IsEdit) { cxt.ModelState.AddModelError("", "Another user changed that product. " + "Click Cancel to see changes."); } else { cxt.ModelState.AddModelError("", "Another user deleted that product."); } }
public void InsertEvent([QueryString] int parkId, ModelMethodContext context) { var item = new Event(); item.ParkID = parkId; context.TryUpdateModel(item); if (context.ModelState.IsValid) { using (db) { db.Events.Add(item); db.SaveChanges(); } } }
public void InsertTrain(ModelMethodContext context) { var item = new StaticTrain(); context.TryUpdateModel(item); item.BlockID = ""; item.Trip_id = ""; ValidateTrain(item); if (context.ModelState.IsValid) { db.StaticTrains.Add(item); db.SaveChanges(); } }
public void UpdateStudent(int studentID, ModelMethodContext context) { ContosoUniversityModelBinding.Models.Student item = null; item = db.Students.Find(studentID); if (item == null) { context.ModelState.AddModelError("", String.Format("Item with id {0} was not found", studentID)); return; } context.TryUpdateModel(item); if (context.ModelState.IsValid) { db.SaveChanges(); } }
// The id parameter name should match the DataKeyNames value set on the control public void DeleteTrain(int StaticTrainId, ModelMethodContext context) { var item = new StaticTrain { StaticTrainId = StaticTrainId }; db.Entry(item).State = EntityState.Deleted; try { db.SaveChanges(); } catch { context.ModelState.AddModelError("", $"Item with id {StaticTrainId} no longer exists in the database."); } }
public void DeleteStudent(int studentID, ModelMethodContext context) { var item = new Student { StudentID = studentID }; db.Entry(item).State = EntityState.Deleted; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { context.ModelState.AddModelError("", String.Format("Item with id {0} no longer exists in the database.", studentID)); } }
Login(LoginViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) { return; } // This doesn't count login failures towards lockout only two-factor // authentication. To enable password failures to trigger lockout, // change to shouldLockout: true - note here we are referencing the // ApplicationUserManager.UserLockoutEnabledByDefault property to set // the default action var result = PasswordSignIn( model.UserName, model.Password, model.RememberMe, shouldLockout: _userManager.UserLockoutEnabledByDefault); switch (result) { case SignInStatus.Success: RedirectToLocal(); return; case SignInStatus.NotVerified: var user = _userManager.FindByName(model.UserName); SendEmailVerificationCode(user, reminder: true); return; case SignInStatus.LockedOut: StateController.Navigate("AccountLocked"); return; case SignInStatus.RequiresTwoFactorAuthentication: StateController.Navigate( "SendTwoFactorCode", new NavigationData { { ReturnUrlKey, StateContext.Data[ReturnUrlKey] } }); return; default: // case SignInStatus.Failure: context.ModelState.AddModelError("", "Invalid login attempt"); return; } }
public void ModificarAlumno(int id_alumno, ModelMethodContext mmc) { using (bd_notasAlumnosContexto bd = new bd_notasAlumnosContexto()) { // Cargar el elemento alumno objAlum = bd.alumnos.Find(id_alumno); if (objAlum == null) { return; } mmc.TryUpdateModel(objAlum); if (mmc.ModelState.IsValid) { // Guardar los cambios bd.SaveChanges(); } } }
public void ModificarNota(int id_alumno, int id_asignatura, ModelMethodContext mmc) { using (bd_notasAlumnosContexto bd = new bd_notasAlumnosContexto()) { alum_asig objAlAs = null; // Cargar el elemento objAlAs = bd.alums_asigs.Find(id_alumno, id_asignatura); if (objAlAs == null) { return; } mmc.TryUpdateModel(objAlAs); if (mmc.ModelState.IsValid) { // Guardar los cambios bd.SaveChanges(); } } }
Register(RegisterViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) { return; } var newUser = CreateUserFromRegistration(model); IdentityResult result = _userManager.Create(newUser, model.Password); if (result.Succeeded) { RegisterNewUser(newUser); return; } AddErrors(result, context); }
public void DeleteEvent(int eventId, ModelMethodContext ctx) { using (db) { var item = new Event { EventID = eventId }; db.Entry(item).State = EntityState.Deleted; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { ctx.ModelState.AddModelError("", String.Format("Item with id {0} no longer exists in the database.", ctx)); } } }
RequestPasswordReset( RequestPasswordResetViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) { return; } // Validate the user password var user = _userManager.FindByEmail(model.Email); if ((user == null) || (!_userManager.IsEmailConfirmed(user.Id))) { context.ModelState.AddModelError( "", "The user either does not exist or is not confirmed."); return; } // For more information on how to enable account confirmation and // password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send email with the code and the redirect to reset password page var code = _userManager.GeneratePasswordResetToken(user.Id); var callbackUrl = GetResetPasswordRedirectUrl(code); _userManager.SendEmail( user.Id, "Reset Password", EmailService.CreatePasswordResetMessage(callbackUrl) ); // Modify this code to remove the code reference for production. // The code value should only be included for demonstration // purposes! StateController.Navigate( "RequestPasswordResetConfirmation", new NavigationData { { CodeKey, code } }); }
ExternalLoginHandler( ExternalLoginHandlerViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) { return; } var newUser = CreateUserFromRegistration(model); var result = _userManager.Create(newUser); if (result.Succeeded) { var loginInfo = _context.GetOwinContext().Authentication .GetExternalLoginInfo(); if (loginInfo == null) { ExternalLoginFailRedirect(); return; } result = _userManager.AddLogin(newUser.Id, loginInfo.Login); if (result.Succeeded) { // Microsoft's default approach does not validate the user's // email address, deferring the authentication to the // third-party provider. // // SignIn(user, isPersistent: false); // RedirectToLocal(); RegisterNewUser(newUser); return; } } AddErrors(result, context); }
public void DeleteProduct(string ProductID, ModelMethodContext ctx) { Product item = GetProductById(ProductID); if (item != null) { db.Products.Remove(item); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { HandleConcurrencyError(ex, ctx, IsEdit: false); } catch (Exception ex) { HandleError(ex, ctx); } } }
ChangePassword( ChangePasswordViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) { return; } var userId = _context.User.Identity.GetUserId(); var result = _userManager.ChangePassword( userId, model.CurrentPassword, model.NewPassword); if (result.Succeeded) { var user = _userManager.FindById(userId); SignIn(user, isPersistent: false); RedirectToManager(ManageMessageId.ChangePasswordSuccess); return; } AddErrors(result, context); }
public void SendTwoFactorCode( SendTwoFactorCodeViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) return; var userId = GetVerifiedUserId(); var user = _userManager.FindById(userId); if (user != null) { var code = _userManager.GenerateTwoFactorToken( user.Id, model.Provider); _userManager.NotifyTwoFactorToken(userId, model.Provider, code); StateController.Navigate( "VerifyTwoFactorCode", new NavigationData { {ProviderNameKey, model.Provider}, {CodeKey, code}, {ReturnUrlKey, StateContext.Bag.ReturnUrl} }); } else { context.ModelState.AddModelError( "", "Unable to identify current user!"); } }
public void ChangePassword( ChangePasswordViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) return; var userId = _context.User.Identity.GetUserId(); var result = _userManager.ChangePassword( userId, model.CurrentPassword, model.NewPassword); if (result.Succeeded) { var user = _userManager.FindById(userId); SignIn(user, isPersistent: false); RedirectToManager(ManageMessageId.ChangePasswordSuccess); return; } AddErrors(result, context); }
public void ExternalLoginHandler( ExternalLoginHandlerViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) return; var newUser = CreateUserFromRegistration(model); var result = _userManager.Create(newUser); if (result.Succeeded) { var loginInfo = _context.GetOwinContext().Authentication .GetExternalLoginInfo(); if (loginInfo == null) { ExternalLoginFailRedirect(); return; } result = _userManager.AddLogin(newUser.Id, loginInfo.Login); if (result.Succeeded) { // Microsoft's default approach does not validate the user's // email address, deferring the authentication to the // third-party provider. // // SignIn(user, isPersistent: false); // RedirectToLocal(); RegisterNewUser(newUser); return; } } AddErrors(result, context); }
GetExternalLoginHandler(ModelMethodContext context) { var model = new ExternalLoginHandlerViewModel { ProviderName = StateContext.Data[ProviderNameKey] as string }; // Check that a Provider is specified if (String.IsNullOrWhiteSpace(model.ProviderName)) { ExternalLoginFailRedirect(); return(null); } var loginInfo = _authenticationManager.GetExternalLoginInfo(); if (loginInfo == null) { ExternalLoginFailRedirect(); return(null); } var signInStatus = ExternalSignIn(loginInfo, false); switch (signInStatus) { case SignInStatus.Success: RedirectToLocal(); return(null); case SignInStatus.NotVerified: var user = _userManager.Find(loginInfo.Login); SendEmailVerificationCode(user, reminder: true); return(null); case SignInStatus.LockedOut: StateController.Navigate("AccountLocked"); return(null); case SignInStatus.RequiresTwoFactorAuthentication: StateController.Navigate( "SendTwoFactorCode", new NavigationData { { ReturnUrlKey, StateContext.Data[ReturnUrlKey] } }); return(null); } if (_context.User.Identity.IsAuthenticated) { // Apply Xsrf check when linking var userId = _context.User.Identity.GetUserId(); var verifiedloginInfo = _authenticationManager .GetExternalLoginInfo(XsrfKey, userId); if (verifiedloginInfo == null) { ExternalLoginFailRedirect(); return(null); } var result = _userManager.AddLogin(userId, verifiedloginInfo.Login); if (result.Succeeded) { RedirectToLocal(); return(null); } AddErrors(result, context); } else { // It's a new account, so get additional local details model.UserName = loginInfo.DefaultUserName; model.Email = loginInfo.Email; } return(model); }
public ExternalLoginHandlerViewModel GetExternalLoginHandler(ModelMethodContext context) { var model = new ExternalLoginHandlerViewModel { ProviderName = StateContext.Data[ProviderNameKey] as string }; // Check that a Provider is specified if (String.IsNullOrWhiteSpace(model.ProviderName)) { ExternalLoginFailRedirect(); return null; } var loginInfo = _authenticationManager.GetExternalLoginInfo(); if (loginInfo == null) { ExternalLoginFailRedirect(); return null; } var signInStatus = ExternalSignIn(loginInfo, false); switch (signInStatus) { case SignInStatus.Success: RedirectToLocal(); return null; case SignInStatus.NotVerified: var user = _userManager.Find(loginInfo.Login); SendEmailVerificationCode(user, reminder: true); return null; case SignInStatus.LockedOut: StateController.Navigate("AccountLocked"); return null; case SignInStatus.RequiresTwoFactorAuthentication: StateController.Navigate( "SendTwoFactorCode", new NavigationData { {ReturnUrlKey, StateContext.Data[ReturnUrlKey]} }); return null; } if (_context.User.Identity.IsAuthenticated) { // Apply Xsrf check when linking var userId = _context.User.Identity.GetUserId(); var verifiedloginInfo = _authenticationManager .GetExternalLoginInfo(XsrfKey, userId); if (verifiedloginInfo == null) { ExternalLoginFailRedirect(); return null; } var result = _userManager.AddLogin(userId, verifiedloginInfo.Login); if (result.Succeeded) { RedirectToLocal(); return null; } AddErrors(result, context); } else { // It's a new account, so get additional local details model.UserName = loginInfo.DefaultUserName; model.Email = loginInfo.Email; } return model; }
public void Login(LoginViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) return; // This doesn't count login failures towards lockout only two-factor // authentication. To enable password failures to trigger lockout, // change to shouldLockout: true - note here we are referencing the // ApplicationUserManager.UserLockoutEnabledByDefault property to set // the default action var result = PasswordSignIn( model.UserName, model.Password, model.RememberMe, shouldLockout: _userManager.UserLockoutEnabledByDefault); switch (result) { case SignInStatus.Success: RedirectToLocal(); return; case SignInStatus.NotVerified: var user = _userManager.FindByName(model.UserName); SendEmailVerificationCode(user, reminder: true); return; case SignInStatus.LockedOut: StateController.Navigate("AccountLocked"); return; case SignInStatus.RequiresTwoFactorAuthentication: StateController.Navigate( "SendTwoFactorCode", new NavigationData { {ReturnUrlKey, StateContext.Data[ReturnUrlKey]} }); return; default: // case SignInStatus.Failure: context.ModelState.AddModelError("", "Invalid login attempt"); return; } }
public void Register(RegisterViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) return; var newUser = CreateUserFromRegistration(model); IdentityResult result = _userManager.Create(newUser, model.Password); if (result.Succeeded) { RegisterNewUser(newUser); return; } AddErrors(result, context); }
public void RequestPasswordReset( RequestPasswordResetViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) return; // Validate the user password var user = _userManager.FindByEmail(model.Email); if ((user == null) || (!_userManager.IsEmailConfirmed(user.Id))) { context.ModelState.AddModelError( "", "The user either does not exist or is not confirmed."); return; } // For more information on how to enable account confirmation and // password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send email with the code and the redirect to reset password page var code = _userManager.GeneratePasswordResetToken(user.Id); var callbackUrl = GetResetPasswordRedirectUrl(code); _userManager.SendEmail( user.Id, "Reset Password", EmailService.CreatePasswordResetMessage(callbackUrl) ); // Modify this code to remove the code reference for production. // The code value should only be included for demonstration // purposes! StateController.Navigate( "RequestPasswordResetConfirmation", new NavigationData { {CodeKey, code} }); }
public void ResetPassword(ResetPasswordViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) return; string code = StateContext.Data[CodeKey] as string; if (code == null) { context.ModelState.AddModelError("", "Invalid call to this page"); return; } var user = _userManager.FindByEmail(model.Email); if (user == null) { context.ModelState.AddModelError("", "User not found!"); return; } var result = _userManager.ResetPassword(user.Id, code, model.Password); if (result.Succeeded) { StateController.Navigate("ResetPasswordConfirmation"); } }
public void ResendVerificationEmail(ModelMethodContext context) { var user = GetCurrentUser(); SendEmailVerificationCode(user, true); }
public void UpdatePersonalDetails( PersonalDetailsViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) return; var user = GetCurrentUser(); user.UserDetails.Title = model.Title; user.UserDetails.FirstName = model.FirstName; user.UserDetails.LastName = model.LastName; user.UserDetails.Gender = model.Gender; user.UserDetails.DateOfBirth = model.DateOfBirth; var result = _userManager.Update(user); if (result.Succeeded) { RedirectToManager(ManageMessageId.UserDetailsUpdateSuccess); return; } AddErrors(result, context); }
ResendVerificationEmail(ModelMethodContext context) { var user = GetCurrentUser(); SendEmailVerificationCode(user, true); }
public void VerifyPhoneNumber( VerifyPhoneNumberViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) return; var userId = _context.User.Identity.GetUserId(); var result = _userManager.ChangePhoneNumber( userId, model.PhoneNumber, model.Code); if (result.Succeeded) { var user = _userManager.FindById(userId); if (user != null) { SignIn(user, false); RedirectToManager(ManageMessageId.AddPhoneSuccess); } } else { context.ModelState.AddModelError("", "Invalid verification code"); } }
public void VerifyTwoFactorCode( VerifyTwoFactorCodeViewModel model, ModelMethodContext context) { if (!context.ModelState.IsValid) return; var result = TwoFactorSignIn( model.Provider, model.Code, isPersistent: false, rememberBrowser: model.RememberBrowser); switch (result) { case SignInStatus.Success: RedirectToLocal(); return; case SignInStatus.LockedOut: StateController.Navigate("AccountLocked"); return; default: context.ModelState.AddModelError("Code", "Invalid Code"); break; } }
/// <summary> /// Evaluates the method parameters using model binding. /// </summary> /// <param name="dataSourceOperation">The datasource operation for which parameters are being evaluated.</param> /// <param name="modelDataSourceMethod">The ModelDataSourceMethod object for which the Parameter collection is being evaluated. The MethodInfo property should already be set on this object.</param> /// <param name="controlValues">The values from the data bound control.</param> /// <param name="isPageLoadComplete">This must be set to true only when this method is called in Page's LoadComplete event handler /// to evaluate the select method parameters that use custom value providers so that we can identify any changes /// to those and mark the data-bound control for data binding if necessary.</param> protected virtual void EvaluateMethodParameters(DataSourceOperation dataSourceOperation, ModelDataSourceMethod modelDataSourceMethod, IDictionary controlValues, bool isPageLoadComplete) { Debug.Assert(_owner.DataControl.Page != null); Debug.Assert(_owner.DataControl.TemplateControl != null); MethodInfo actionMethod = modelDataSourceMethod.MethodInfo; IModelBinder binder = ModelBinders.Binders.DefaultBinder; IValueProvider dataBoundControlValueProvider = GetValueProviderFromDictionary(controlValues); ModelBindingExecutionContext modelBindingExecutionContext = _owner.DataControl.Page.ModelBindingExecutionContext; Control previousDataControl = null; if (BinaryCompatibility.Current.TargetsAtLeastFramework46) { // DevDiv 1087698: a child control overwrites its parent controls's modelBindingExecutionContext, // which may cause a problem for the parent control to find control by controlId. Control dataControl = modelBindingExecutionContext.TryGetService<Control>(); if (dataControl != _owner.DataControl) { previousDataControl = dataControl; } } //This is used by ControlValueProvider later. modelBindingExecutionContext.PublishService<Control>(_owner.DataControl); //This is done for the TryUpdateModel to work inside a Data Method. if (dataSourceOperation != DataSourceOperation.Select) { _owner.DataControl.Page.SetActiveValueProvider(dataBoundControlValueProvider); } var methodParameters = actionMethod.GetParameters(); ParameterInfo lastParameter = null; if (methodParameters.Length > 0) { lastParameter = methodParameters[methodParameters.Length - 1]; } foreach (ParameterInfo parameterInfo in methodParameters) { object value = null; string modelName = parameterInfo.Name; if (parameterInfo.ParameterType == typeof(ModelMethodContext)) { //ModelMethodContext is a special parameter we pass in for enabling developer to call //TryUpdateModel when Select/Update/Delete/InsertMethods are on a custom class. value = new ModelMethodContext(_owner.DataControl.Page); } //Do not attempt model binding the out parameters else if (!parameterInfo.IsOut) { bool validateRequest; IValueProvider customValueProvider = GetCustomValueProvider(modelBindingExecutionContext, parameterInfo, ref modelName, out validateRequest); //When we are evaluating the parameter at the time of page load, we do not want to populate the actual ModelState //because there will be another evaluation at data-binding causing duplicate errors if model validation fails. ModelStateDictionary modelState = isPageLoadComplete ? new ModelStateDictionary() : _owner.DataControl.Page.ModelState; ModelBindingContext bindingContext = new ModelBindingContext() { ModelBinderProviders = ModelBinderProviders.Providers, ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, parameterInfo.ParameterType), ModelState = modelState, ModelName = modelName, ValueProvider = customValueProvider, ValidateRequest = validateRequest }; //Select parameters that take custom values providers are tracked by ViewState so that //we can detect any changes from previous page request and mark the data bound control for data binding if necessary. if (dataSourceOperation == DataSourceOperation.Select && customValueProvider != null && parameterInfo.ParameterType.IsSerializable) { if (!SelectParameters.ContainsKey(parameterInfo.Name)) { SelectParameters.Add(parameterInfo.Name, new MethodParameterValue()); } if (binder.BindModel(modelBindingExecutionContext, bindingContext)) { value = bindingContext.Model; } SelectParameters[parameterInfo.Name].UpdateValue(value); } else { if (isPageLoadComplete) { Debug.Assert(dataSourceOperation == DataSourceOperation.Select, "Only Select Operation should have been done immediately after page load"); //When this method is called as part of Page's LoadComplete event handler we do not have values in defaultValueProvider //(i.e., values from DataBoundControl), so we need not evaluate the parameters values. continue; } if (customValueProvider == null) { bindingContext.ValueProvider = dataBoundControlValueProvider; } if (binder.BindModel(modelBindingExecutionContext, bindingContext)) { value = bindingContext.Model; } } // We set the CancellationToken after EvaluateMethodParameters(). // We don't want to set a null value to a CancellationToken variable. if (parameterInfo == lastParameter && typeof(CancellationToken) == parameterInfo.ParameterType && value == null) { value = CancellationToken.None; } if (!isPageLoadComplete) { ValidateParameterValue(parameterInfo, value, actionMethod); } } modelDataSourceMethod.Parameters.Add(parameterInfo.Name, value); } if (previousDataControl != null) { modelBindingExecutionContext.PublishService<Control>(previousDataControl); } }