ASP.NET MVC return PartialViewResult - asp.net-mvc-3

I made a form with #using(Ajax.BeginForm){}. It posts to a method in my controller that returns a PartialViewResult. It works fine when everything is valid, but what should I return if
it's not (e.g., the modelstate is not valid)?
How Ajax.BeginForm can manage the error? What I return to manage the Failure?
#using(Ajax.BeginForm("Create", "Room", new AjaxOptions { HttpMethod="POST",
UpdateTargetId="formRoom", InsertionMode= InsertionMode.Replace, onFailure =??})) {
public PartialViewResult Create(Movie mov)
{
if (ModelState.IsValid)
{
db.Save(mov);
return PartialView("CreateResult", mov);
}
return null;
}
Thanks!

You may return another View.
e.g. return PartialView("MyErrorView");

Just return Create action with the model to display the errors (the same as you returned on your get):
[HttpPost]
public PartialViewResult PartialCreate(Album album)
{
if (ModelState.IsValid)
{
db.Albums.Add(album);
db.SaveChanges();
return PartialView("Index");
}
ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
return PartialView(album);
}

Related

Multiple Forms in MVC5

I have an HTML Form devided into six sections. On each section the user clicks on the "Next Page" to move forwards. Or "Previous Page" to go back. At the end of the sixth section it has a "SAVE" button. I am assuming the data does not get saved until the very end.
I need to convert this into MVC application. Is there an easy way to handle this?
--UPDATE I am thinking something like this. Does this make any sense?
[HttpPost]
public ActionResult Step1(Step1ViewModel model)
{
if (ModelState.IsValid)
{
Session["Step1"] = model;
return RedirectToAction("Step2");
}
// errors
return View(model);
}
[HttpPost]
public ActionResult Step2(Step2ViewModel model)
{
if (ModelState.IsValid)
{
Session["Step2"] = model;
return RedirectToAction("Step3");
}
// errors
return View(model);
}
[HttpPost]
public ActionResult Step3(Step3ViewModel model)
{
if (ModelState.IsValid)
{
Session["Step3"] = model;
return RedirectToAction("Step4");
}
// errors
return View(model);
}
You should store the data of each "section" in the session, when you call the "Next Page" method.

Is this the correct way to save form values in MVC3?

Here's my code:
[HttpGet]
public ActionResult Register()
{
RegisterViewModel model = new RegisterViewModel();
using (CityRepository city = new CityRepository())
{
model.SelectCityList = new SelectList(city.FindAllCities().ToList(), "CityID", "CityName");
}
using (CountryRepository country = new CountryRepository())
{
model.SelectCountryList = new SelectList(country.FindAllCountries().ToList(), "CountryID", "CountryName");
}
return View(model);
}
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
//Actually register the user here.
RedirectToAction("Index", "Home");
}
//Something went wrong, redisplay the form for correction.
return View(model);
}
Is this the best approach or is there another better tested way? Keep in mind that my database tables/field names are nothing like what I declared in my models. I have to scrape the values from the ViewModel and put them into an entity framework generated class to persist the information.
Anything here that screams out at you as wrong?
I use that pattern and another pattern which looks like this (important part is the AutoMapper part):
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
{
// repopulate any input or other items set in GET
// prefer to do at top due to ^^^ is easy to overlook
return View(model);
}
// if it's an edit, pull to new instance
// from the database and use automapper to
// map over the submitted values from model to instance
// then update instance in database
//
// VALUE: useful if form only shows
// some of the properties/fields of model
// (otherwise, those not shown would be null/default)
// if it's new, insert
RedirectToAction("Index", "Home");
}
That's the pattern I generally use.
I prefer this pattern:
Controller:
[HttpGet]
public ActionResult Index()
{
var cities= (from m in db.cities select m);
ViewBag.Cities= cities;
var states = (from m in db.States select m);
ViewBag.States = states;
return View();
}
[HttpPost]
public ActionResult Index(RegisterViewModel model)
{
if (ModelState.IsValid)
{
// Saving the data
return View("ActionName", model);
}
return View();
}
View:
#Html.DropDownList("DDLCities",new SelectList(ViewBag.Cities, "CityId" , "CityName" ), new { #class = "className" })
#Html.DropDownList("DDLStates",new SelectList(ViewBag.States, "StateId" , "StateName" ), new { #class = "className" })
Advised changes to [HttpGet]:
[HttpGet]
public ActionResult Register()
{
// Get
var cities = new List<City>();
var countries = new List<Country>();
using (CityRepository city = new CityRepository())
{
cities = city.FindAllCities().ToList();
}
using (CountryRepository country = new CountryRepository())
{
counties = country.FindAllCountries().ToList();
}
// Map.
var aggregatedObjects = new SomePOCO(cities, countries);
var model = Mapper.Map<SomePOCO,RegisterViewModel>(aggregatedObjects );
// Return
return View(model);
}
Summary of changes:
Layout your logic in such a way the controller's job makes sense. Get - Map - Return. Exactly the tasks (in order) for which a Controller is designed for.
Use AutoMapper to do the heavy lifting of ViewModel creation for you.
Advised changes to your [HttpPost]:
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
return View(model);
try
{
var dbObj = Mapper.Map<RegisterViewModel,SomeDomainObj>(model);
_repository.Save(dbObj);
return RedirectToAction("Index");
}
catch (Exception exc)
{
if (exc is BusinessError)
ModelState.AddModelError("SomeKey", ((BusinessError)exc).FriendlyError);
else
ModelState.AddModelError("SomeKey", Resources.Global.GenericErrorMessage);
}
return View(model);
}
Summary of changes:
Try/catch. Always need to capture exceptions, whether they are domain exceptions or lower-level (database ones)
Check ModelState validity first. As #Cymen says - do it first so you don't forget later
Add exceptions to ModelState. Use custom exception classes for business errors with descriptive, resource-based messages. If the error is too low-level for the user (foreign key constraint, etc), show a generic message

Error while creating new database record in asp.net mvc

I'm new to asp.net mvc. However, this is what I've done:
In the controller,
public ActionResult Create()
{
return View();
}
//
// POST: /Customerservice/Create
[HttpPost]
public ActionResult Create([Bind(Exclude="CustomerServiceMappingID")] Maping serviceToCreate)
{
if (!ModelState.IsValid)
return View();
var dc = new ServicesDataContext();
dc.Mapings.InsertOnSubmit(serviceToCreate);
dc.SubmitChanges();
return RedirectToAction("Index","Home");
}
The View goes like this:
#Html.DropDownListFor(model => model.Status, new SelectList(new List<object>
{new {value="Active" , text="Active"},
new {value="Pending", text="Pending" },
new {value="Disabled", text="Disabled"}}, "value", "text", Model.Status))
There are 4 fields. However, when I try to use Status , I get an exception saying " Object Reference not set to an instance of object"
In the GET action you need to pass the model to the view:
public ActionResult Create()
{
// the model could also be fetched from the DB given
// an unique ID passed as argument to this action
var model = new Maping();
return View(model);
}

RedirectToAction after validation errors

If I have the usual Edit actions, one for GET to retrieve an object by it's ID and to display it in an edit form. The next for POST to take the values in the ViewModel and update the object in the database.
public virtual ActionResult Edit(int id)
[HttpPost]
public ActionResult Edit(VehicleVariantEditSaveViewModel viewModel)
If an error occurs during model binding in the POST action, I understand I can RedirectToAction back to the GET action and preserve the ModelState validation errors by copying it to TempData and retrieving it after the redirect in the GET action.
if (TempData["ViewData"] != null)
{
ViewData = (ViewDataDictionary)TempData["ViewData"];
}
How do I then convert that ViewData, which includes the previous invalid ModelState, into a new model to send to the view so the user sees their invalid input with validation warnings? Oddly enough if I pass in a new instance of my ViewModel retrieved from the database (with the original valid data) to the View() this is ignored and the (invalid) data in the ViewData is displayed!
Thanks
I had a similar problem and decided to use the following pattern:
public ActionResult PersonalRecord(Guid id)
{
if (TempData["Model"] == null)
{
var personalRecord = _context.PersonalRecords.Single(p => p.UserId == id);
var model = personalRecord.ToPersonalRecordModel();
return View(model);
}
else
{
ViewData = (ViewDataDictionary) TempData["ViewData"];
return View(TempData["Model"]);
}
}
[HttpPost]
public ActionResult PersonalRecord(PersonalRecordModel model)
{
try
{
if (ModelState.IsValid)
{
var personalRecord = _context.PersonalRecords.Single(u => u.UserId == model.UserId);
personalRecord.Email = model.Email;
personalRecord.DOB = model.DOB;
personalRecord.PrimaryPhone = model.PrimaryPhone;
_context.Update(personalRecord);
_context.SaveChanges();
return RedirectToAction("PersonalRecord");
}
}
catch (DbEntityValidationException ex)
{
var errors = ex.EntityValidationErrors.First();
foreach (var propertyError in errors.ValidationErrors)
{
ModelState.AddModelError(propertyError.PropertyName, propertyError.ErrorMessage);
}
}
TempData["Model"] = model;
TempData["ViewData"] = ViewData;
return RedirectToAction("PersonalRecord", new { id = model.UserId });
}
Hope this helps.
I noticed that the Model is included in ViewData so you don't need to pass it in addition to the ViewData, what I don't understand is how you get at it to then return it to the view.
public ViewResult Edit(int id)
{
// Check if we have ViewData in the session from a previous attempt which failed validation
if (TempData["ViewData"] != null)
{
ViewData = (ViewDataDictionary)TempData["ViewData"];
}
VehicleVariantEditViewModel viewModel = new VehicleVariantControllerViewModelBuilder()
.BuildForEdit(id);
return View(viewModel);
}
The above works but obviously it's making an unnecessary call to the database to build a new Model (which gets automagically overwritten with the invalid values from the Model in the passed ViewData)
Confusing.

MVC Delete record but how to code this in Controller

I'm a beginner of MVC3 with ASP.Net (C#) but I don't get the next situation to delete a record.
I have a View that ask the user to confirm delete a item (record). As code I have this to initialize the view:
public ActionResult KeywordsDelete(Guid id)
{
_db = new BlaContext();
return _db.SearchTerms.Where(x => x.id.Equals(id)).First();
}
But when confirmed, then I have the next code.
[HttpPost]
public ActionResult KeywordsDelete(Guid id)
{
_db = new BlaContext();
var term = _db.SearchTerms.Where(x => x.id == id).First();
_db.SearchTerms.Remove(term);
_db.SaveChanges();
return View("Keywords", _db.SearchTerms.ToList());
}
Building is not possible because the signature of this method is already exists (same parameters and method name).
So I don't get how to delete a record in this situation. The view is created with a default Scaffold template (delete).
I found an alternative solution to this problem while reading up on MVC. Check out: Improving the Details and Delete Methods
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id = 0)
{
// Delete stuff...
}
This will route the action Delete to the method DeleteConfirmed.
You can give your post function another additional parameter
[HttpPost]
public ActionResult KeywordsDelete(Guid id, FormCollection collection)
{
_db = new BlaContext();
var term = _db.SearchTerms.Where(x => x.id == id).First();
_db.SearchTerms.Remove(term);
_db.SaveChanges();
return View("Keywords", _db.SearchTerms.ToList());
}
But your GET Action should also return a View not a data object, I think.
public ActionResult KeywordsDelete(Guid id)
{
_db = new BlaContext();
return View(_db.SearchTerms.Where(x => x.id.Equals(id)).First());
}

Resources