public ActionResult Edit(int id, FormCollection forms) { if (id == 0) { CmsMenu newMenu = new CmsMenu() { Title = forms.GetValue("Title").AttemptedValue, Description = forms.GetValue("Description").AttemptedValue, Type = forms.GetValue("Type").AttemptedValue }; if (newMenu.IsValid) { return this.CreateNewMenu(newMenu); } ModelState.AddModelErrors(newMenu.GetRuleViolations()); return View(newMenu); } CmsMenu menu = this.menuService.LoadMenu(id); UpdateModel(menu, forms.ToValueProvider()); this.menuService.SaveMenu(menu); TempData["SuccessResult"] = "Menu was successfully saved"; return this.View(menu); }
public ActionResult Create(FormCollection collection) { var model = new Role(); TryUpdateModel(model, collection.ToValueProvider()); if (!ModelState.IsValid) { return View(model); } using (var session = new SessionFactory().OpenSession()) { if (session.Load<Role>(m => m.Name.Equals(model.Name)) != null) { FlashFailure("角色名称[{0}]已经存在,创建失败!", model.Name); return View(model); } model.CreatedAt = DateTime.Now; model.CreatedBy = CurrentAccountNo; ViewData.Model = model; if (session.Create(model)) { FlashSuccess("角色[{0}]创建成功", model.Name); return Close(); } FlashFailure("创建角色[{0}]失败!", model.Name); return View(model); } }
public ActionResult Create(FormCollection collection, long id = 0) { var model = new TrainManagementItem { TrainManId = id }; TryUpdateModel(model, collection.ToValueProvider()); if (!ModelState.IsValid) { return View(model); } using (var session = new SessionFactory().OpenSession()) { session.BeginTransaction(); var trainMan = session.Load<TrainManagement>(id); if (trainMan == null) { FlashError("培训不存在,请联系管理员!"); return Close(); } model.Year = trainMan.Year; model.TrainManName = trainMan.Name; model.CreatedAt = DateTime.Now; model.CreatedBy = CurrentAccountNo; ViewData.Model = model; if (session.Create(model)) { session.Commit(); FlashSuccess("创建记录成功!"); return Close(); } session.Rollback(); FlashFailure("创建记录失败!"); return View(); } }
public void posting_invalid_data_to_edit_returns_view_and_adds_modelerror() { //arrange var id = 1; var name = string.Empty; var subject = "Welcome to Springfield!"; var text = "Lorem ipsum dolor sit amet."; var html = "<p>Lorem <b>ipsum</b> dolor sit amet.</p>"; var form = new FormCollection{ { "Name", name }, { "Subject", subject }, { "Text", text }, { "Html", html } }; controller.ValueProvider = form.ToValueProvider(); var ex = new ValidationException( new List<ValidationError>{ new ValidationError( "Name", "Name is a required field." ) } ); service.Expect( x => x.Update( It.IsAny<Message>() ) ).Throws( ex ); //act var result = controller.Edit_Post( id ); //assert Assert.IsAssignableFrom( typeof(ViewResult), result ); var viewResult = (ViewResult)result; Assert.AreEqual( "", viewResult.ViewName ); Assert.IsFalse( viewResult.ViewData.ModelState.IsValid ); }
public ActionResult Register(FormCollection form) { _db = new renoRatorDBEntities(); var newUser = new RegisterModel(); //temp newUser.userTypeID = 1; // Deserialize (Include white list!) TryUpdateModel(newUser, new string[] { "fname", "lname", "email", "password" }, form.ToValueProvider()); // Validate if (String.IsNullOrEmpty(newUser.fname)) ModelState.AddModelError("fname", "First name is required!"); if (String.IsNullOrEmpty(newUser.lname)) ModelState.AddModelError("lname", "Last name is required!"); if (String.IsNullOrEmpty(newUser.email)) ModelState.AddModelError("email", "Email is required!"); if (String.IsNullOrEmpty(newUser.password)) ModelState.AddModelError("password", "Password is required!"); if (newUser.password != form["passwordConfirm"]) ModelState.AddModelError("passwordConfirm", "Passwords don't match!"); if (newUser.email != form["emailConfirm"]) ModelState.AddModelError("emailConfirm", "Email addresses don't match!"); // If valid, save movie to database if (ModelState.IsValid) { newUser.Save(); return RedirectToAction("Home"); } // Otherwise, reshow form return View(newUser); }
public ActionResult Create(FormCollection collection) { var model = new SchoolDepartment(); TryUpdateModel(model, collection.ToValueProvider()); if (!ModelState.IsValid) { return View(model); } using (var session = new SessionFactory().OpenSession()) { //model.ParentId //model.LeaderId model.LeaderName = model.LeaderId == 0 ? "" : session.Load<User>(model.LeaderId).Realname; if (session.Load<SchoolDepartment>(m => m.Name.Equals(model.Name)) != null) { FlashFailure("部门[{0}]已经存在", model.Name); return View(model); } model.CreatedAt = DateTime.Now; model.CreatedBy = CurrentAccountNo; ViewData.Model = model; if (session.Create(model)) { FlashSuccess("部门[{0}]创建成功", model.Name); return Close(); } FlashFailure("创建部门[{0}]失败!", model.Name); return View(); } }
public ActionResult Editar(int id, FormCollection collection) { var model = repository.Clientes.First(p => p.ClienteId == id); try { TryUpdateModel(model, new string[] { "ClienteId", "Nombre", "Apellido", "Direccion", "Email", "Telefono" }, collection.ToValueProvider()); // Validadte if (String.IsNullOrEmpty(model.Nombre.ToString())) ModelState.AddModelError("Nombre", "El Nombre es Requerido"); if (ModelState.IsValid) { repository.SaveDB(); return RedirectToAction("Index"); } } catch { return View(); } return View(model); }
public ActionResult Create(FormCollection collection) { var movieToCreate = new Movie(); this.UpdateModel(movieToCreate, collection.ToValueProvider()); // Insert movie into database return RedirectToAction("Index"); }
public ActionResult Create(FormCollection collection) { //var item = new User(); var item = new User() { CreatedOn = DateTime.Now}; //please don't omit this... var whiteList=new string[]{"UserName","OpenID","Friendly","LastLogin","ModifiedOn"}; UpdateModel(item,whiteList,collection.ToValueProvider()); var dummy = item; if(ModelState.IsValid){ try { _session.Add<User>(item); _session.CommitChanges(); this.FlashInfo("User saved..."); return RedirectToAction("Index"); } catch { this.FlashError("There was an error saving this record"); return View(item); } } return View(item); }
public ActionResult Create(FormCollection collection) { var model = new TrainManagement(); TryUpdateModel(model, collection.ToValueProvider()); if (!ModelState.IsValid) { return View(model); } using (var session = new SessionFactory().OpenSession()) { session.BeginTransaction(); model.CreatedAt = DateTime.Now; model.CreatedBy = CurrentAccountNo; ViewData.Model = model; if (session.Create(model)) { session.Commit(); FlashSuccess("创建记录成功!"); return Close(); } session.Rollback(); FlashFailure("创建记录失败!"); return View(); } }
public ActionResult Edit(FormCollection collection, long[] ids) { if (ids.Length == 0) { FlashWarn("请选择要修改的记录。"); return Close(); } using (var session = new SessionFactory().OpenSession()) { var model = session.Load<School>(m => m.Id.In(ids)); if (model == null) { FlashInfo("你没有选择任何可以修改的学校。"); return Close(); } TryUpdateModel(model, collection.ToValueProvider()); if (!ModelState.IsValid) { return View(model); } model.UpdatedAt = DateTime.Now; model.UpdatedBy = CurrentAccountNo; if (session.Update(model)) { FlashSuccess("学校更改成功"); return Close(); } return View(); } }
public void BinderShouldBindValues() { var controllerContext = new ControllerContext(); var binders = new ModelBinderDictionary { { typeof(Foo), new DefaultModelBinder() } }; var input = new FormCollection { { "fooInstance[Bar1].Value", "bar1value" }, { "fooInstance[Bar2].Value", "bar2value" } }; var foos = new[] { new Foo {Name = "Bar1", Value = "uno"}, new Foo {Name = "Bar2", Value = "dos"}, new Foo {Name = "Bar3", Value = "tres"}, }; var providers = new EmptyModelMetadataProvider(); var bindingContext = new ModelBindingContext { ModelMetadata = providers.GetMetadataForType(() => foos, foos.GetType()), ModelName = "fooInstance", ValueProvider = input.ToValueProvider() }; var binder = new KeyedListModelBinder<Foo>(binders, providers, foo => foo.Name); var result = (IList<Foo>)binder.BindModel(controllerContext, bindingContext); Assert.That(result.Count, Is.EqualTo(3)); Assert.That(result[0].Value, Is.EqualTo("bar1value")); Assert.That(result[1].Value, Is.EqualTo("bar2value")); }
public ActionResult Approve(FormCollection collection, long[] ids, long id = 0) { if (ids.Length == 0) { FlashWarn("请选择要批阅的记录。"); return Close(); } using (var session = new SessionFactory().OpenSession()) { var model = session.Load<TrainRecordFile>(m => m.Id.In(ids)); if (model == null) { FlashInfo("你没有选择任何可以批阅的记录。"); return Close(); } TryUpdateModel(model, collection.ToValueProvider()); model.UpdatedAt = DateTime.Now; model.UpdatedBy = CurrentAccountNo; if (session.Update(model)) { FlashSuccess("批阅记录成功"); return Close(); } FlashFailure("批阅记录失败,请联系管理员!"); return View(); } }
public ActionResult CreateIngredient(Ingredient ingredient, FormCollection form) { //if (ModelState.IsValid) //{ //Ingredient ingredient = new Ingredient(); // Deserialize (Include white list!) bool isModelUpdated = TryUpdateModel(ingredient, new[] { "IngredientName" }, form.ToValueProvider()); // Validate if (String.IsNullOrEmpty(ingredient.IngredientName)) ModelState.AddModelError("IngredientName", "Ingredient Name is required!"); if (ModelState.IsValid) { var newIngredient = _ingredientApplicationService.CreateIngredient(ingredient.IngredientName); if (newIngredient != null) { return RedirectToAction("EditIngredient", new{id = newIngredient.Id}); } ModelState.AddModelError("IngredientName", "Ingredient or AlternativeIngredientName already exists!"); } return View(ingredient); }
public ActionResult Add(FormCollection form) { var individualToAdd = new Individual(); // Deserialize (Include white list!) TryUpdateModel(individualToAdd, new string[] { "Name", "DateOfBirth" }, form.ToValueProvider()); // Validate if (String.IsNullOrEmpty(individualToAdd.Name)) ModelState.AddModelError("Name", "Name is required!"); if (String.IsNullOrEmpty(individualToAdd.DateOfBirth)) ModelState.AddModelError("DateOfBirth", "DateOfBirth is required!"); var error = individualToAdd.ValidateDateOfBirth(); if (!String.IsNullOrEmpty(error)) ModelState.AddModelError("DateOfBirth", error); // If valid, save Individual to Database if (ModelState.IsValid) { _db.AddToIndividuals(individualToAdd); _db.SaveChanges(); return RedirectToAction("Add"); } // Otherwise, reshow form return View(individualToAdd); }
public ActionResult Edit(int id, FormCollection collection) { DispatchModel form = new DispatchModel(); try { TryUpdateModel<DispatchModel>(form, collection.ToValueProvider()); int rowsAffected = DispatchDAO.UpdateForm(form); } catch { return View(); } try { return RedirectToAction("Edit", new { id = form.FormID }); } catch { return RedirectToAction("Index"); } }
public ActionResult Index(FormCollection collection) { var item = new Upload(); var whiteList = new string[] { "Artist", "Name", "Tab", "BookId" }; if (TryUpdateModel(item, whiteList, collection.ToValueProvider())) { if (ModelState.IsValid) { //_uploadService.Upload(item.Artist, item.Name, item.BookId, item.Tab, User.Identity.Name); var tab = new Tab { Artist = item.Artist, Name = item.Name, Content = item.Tab, CreatedOn = DateTime.UtcNow, AuthorName = User.Identity.Name }; RavenSession.Store(tab); if (item.BookId > 0) { var bookTasks = new BookTasks(); bookTasks.AddTabToBook(tab.Id, item.BookId.Value); } TempData.Add(Constants.TempDataMessage, "Upload successful, thanks!"); return RedirectToAction("Index", "Songs"); } } return View(); }
public void ToValueProviderWrapsCollectionInDictionary() { // Arrange FormCollection fc = new FormCollection() { { "foo", "fooValue0" }, { "foo", "fooValue1" } }; // Act IDictionary<string, ValueProviderResult> valueProvider; using (ValueProviderDictionaryTest.ReplaceCurrentCulture("fr-FR")) { valueProvider = fc.ToValueProvider(); } // Assert Assert.IsNotNull(valueProvider); Assert.AreEqual(1, valueProvider.Count); ValueProviderResult vpResult = valueProvider["foo"]; string[] rawValue = (string[])vpResult.RawValue; Assert.AreEqual(2, rawValue.Length); Assert.AreEqual("fooValue0", rawValue[0]); Assert.AreEqual("fooValue1", rawValue[1]); Assert.AreEqual("fooValue0,fooValue1", vpResult.AttemptedValue); Assert.AreEqual(CultureInfo.GetCultureInfo("fr-FR"), vpResult.Culture); }
public ActionResult Create(FormCollection collection) { var model = new SchoolSection(); TryUpdateModel(model, collection.ToValueProvider()); if (!ModelState.IsValid) { return View(model); } using (var session = new SessionFactory().OpenSession()) { session.BeginTransaction(); if (session.Load<SchoolSection>(m => m.Name.Equals(model.Name)) != null) { FlashWarn("校区{0}已经存在,创建失败。", model.Name); return View(model); } model.CreatedAt = DateTime.Now; model.CreatedBy = CurrentAccountNo; ViewData.Model = model; if (session.Create(model)) { session.Commit(); FlashSuccess("创建校区[{0}]成功!", model.Name); return Close(); } session.Rollback(); FlashFailure("创建校区[{0}]失败!", model.Name); return View(); } }
SagePayBinder SetupBinder(FormCollection post) { bindingContext = new ModelBindingContext { ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(SagePayResponse)), ValueProvider = post.ToValueProvider() }; return new SagePayBinder(); }
public ActionResult Edit(int id, FormCollection form) { var cow = cowRepository.FindById(id); UpdateModel(cow, form.ToValueProvider()); TempData["notice"] = "Cow successfully saved."; return RedirectToAction("Edit", new { id }); }
public ActionResult Edit(AdminEditPageViewModel vm, FormCollection forms, string userName) { CmsPage pageFromDb = pageService.Load(vm.Page.Id); // workaround: update status should be before update model. It's because of defect in asp.net mvc 2 UpdatePageStatus(pageFromDb, forms.ToValueProvider()); UpdateModel(pageFromDb, "Page", forms.ToValueProvider()); pageFromDb.TagString = forms.GetValue("Tags"); if (pageFromDb.IsValid) { pageService.Save(pageFromDb, userName); TempData["SuccessResult"] = "Items was successfully saved"; return RedirectToAction("Edit", new {id = pageFromDb.Id}); } ModelState.AddModelErrors(pageFromDb.GetRuleViolations()); return View(new AdminEditPageViewModel {Page = pageFromDb, PageStatuses = GetStatuses()}); }
public ActionResult Edit([ARFetch("id")] Person person, FormCollection collection) { try { UpdateModel(person, collection.ToValueProvider()); ActiveRecordMediator<Person>.Update(person); return RedirectToAction("Index"); } catch { return View(); } }
public void HomeControllerTestSetUp() { controller = new HomeController(new MockTouristGuideDB()); var routeData = new RouteData(); var httpContext = MockRepository.GenerateStub<HttpContextBase>(); FormCollection formParameters = new FormCollection(); ControllerContext controllerContext = MockRepository.GenerateStub<ControllerContext>(httpContext, routeData, controller); controller.ControllerContext = controllerContext; controller.ValueProvider = formParameters.ToValueProvider(); }
public ActionResult Create(FormCollection collection) { try { var p = new Person(); UpdateModel(p, collection.ToValueProvider()); ActiveRecordMediator<Person>.Save(p); return RedirectToAction("Index"); } catch { return View(); } }
public ActionResult LoginResultUpdateFormCollection(FormCollection collection) { var account = new Account(); this.UpdateModel(account, collection.ToValueProvider()); if (account.Name == "Vahid" && account.Password == "123") ViewBag.Message = "Succeeded"; else ViewBag.Message = "Failed"; return View("Result"); }
public ActionResult Edit(int? id, FormCollection forms) { IEnumerable<SelectListItem> menuTypes = GetMenuTypes(); var vm = new ViewModelMenuItem { MenuTypes = menuTypes }; if (id == null) { return CreateNewMenuItem(vm, menuTypes, forms); } vm.MenuItem = menuService.LoadMenuItem(id.Value); int newId; int prevId = 0; if (null != vm.MenuItem.Entry) { prevId = vm.MenuItem.Entry.Id; } UpdateModel(vm.MenuItem, "MenuItem", new[] {"Id", "CreatedAt", "MenuId", "Title", "NavigateUrl", "Visible"}, forms.ToValueProvider()); bool isExternal = false; bool.TryParse(Request.Form.GetValues("MenuItem.IsExternalUrl")[0], out isExternal); if (isExternal) { vm.MenuItem.Entry = null; } else { vm.MenuItem.NavigateUrl = string.Empty; } if (Int32.TryParse(forms["MenuItem.Entry.Id"], out newId) && newId != prevId) { vm.MenuItem.Entry = pageService.Load(newId); menuService.SaveMenuItem(vm.MenuItem); } else { menuService.SaveMenuItem(vm.MenuItem); } TempData["SuccessResult"] = "MenuItem was successfully updated"; return RedirectToAction("Edit", "MenuItem", new {id = vm.MenuItem.Id}); }
public void all_parameters_are_bound() { var form = new FormCollection() { { "Name", "test_name" } }; var context = new ModelBindingContext() { ValueProvider = form.ToValueProvider(), ModelType = typeof(CodeCamp) }; var mb = new DefaultModelBinder(); var codeCamp = (CodeCamp) mb.BindModel(null, context); Assert.That(codeCamp.Name, Is.EqualTo("test_name")); }
public object Edit(int id, FormCollection form) { Product product = repository.Products.SingleOrDefault(p => p.ProductID == id); if (TryUpdateModel(product, form.ToValueProvider()) && Validate(product)) { repository.SubmitChanges(); return RedirectToAction("List", new { id = product.Category.CategoryName }); } ViewData["CategoryID"] = new SelectList(repository.Categories.ToList(), "CategoryID", "CategoryName", ViewData["CategoryID"] ?? product.CategoryID); ViewData["SupplierID"] = new SelectList(repository.Suppliers.ToList(), "SupplierID", "CompanyName", ViewData["SupplierID"] ?? product.SupplierID); return View(product); }
public ActionResult Create(FormCollection collection) { var model = new TrainNeed(); TryUpdateModel(model, collection.ToValueProvider()); if (!ModelState.IsValid) { return View(model); } using (var session = new SessionFactory().OpenSession()) { session.BeginTransaction(); var dept = new Criteria<Department>(session) .AndIn<User>(m => m.Id, n => n.DepartmentId, m => m.Code.Equals(CurrentAccountNo)).Load(); var models = session.Find<TrainNeed>(m => !m.IsCollected && m.Status.Equals(TrainNeedStatus.已提交部门负责人) && m.DeptId == dept.Id && m.Type.Equals(TrainNeedType.员工)); if (models == null || !models.Any()) { FlashWarn("没有未汇总的需求!"); return Close(); } foreach (var trainNeed in models) { trainNeed.IsCollected = true; } model.DeptId = dept != null ? dept.Id : 0; model.Dept = dept != null ? dept.Name : null; model.IsCollected = false; model.CreatedAt = DateTime.Now; model.CreatedBy = CurrentAccountNo; model.Type = TrainNeedType.部门; ViewData.Model = model; ViewData["StaffNeeds"] = models; var exist = session.Load<TrainNeed>(m => m.Type.Equals(TrainNeedType.部门) && m.DeptId.Equals(model.DeptId) && m.Year.Equals(model.Year)); if (exist != null) { ModelState.AddModelError("Year", "本部门该年度部门培训需求已经存在!"); return View(model); } if (session.Create(model) && session.Update(models)) { session.Commit(); FlashSuccess("创建记录成功!"); return Close(); } session.Rollback(); FlashFailure("创建记录失败!"); return View(); } }