How to use a separate model class for validation in MVC - c#

I am not sure on how to implement this, I have a MovieController.cs in the Controllers folder and a MovieCreateViewModel.cs in the Models folder. I need to add validation for the create, edit and delete views.
MovieDetailsViewModel.cs
public class MovieDetailsViewModel
{
public int Id { get; set; }
}
then I have MovieController.cs
public class MovieController : Controller
{
Connect connection;
MovieCreateViewModel movie;
MovieDetailsViewModel id;
public MovieController()
{
this.connection = new Connect();
this.movie = new MovieCreateViewModel();
this.id = new MovieDetailsViewMode();
}
public ActionResult Edit(MovieDetailsViewModel id)
{
movie = this.connection.MovieContext.Where(m => m.ID == id).SingleOrDefault(); **//I get an error here**
return View(movie);
}
//
// POST: /Movie/Edit/5
[HttpPost]
public ActionResult Edit(MovieCreateViewModel movieedit)
{
try
{
if (ModelState.IsValid)
{
this.connection.MovieContext.AddObject(movieedit);
this.connection.MovieContext.Context.SaveChanges();
return RedirectToAction("Index");
}
}
catch
{
return View(movieedit);
}
}
for the httpPost I made the type MovieDetailsViewModel id in the parameter list
Where do I go from here please?
Thanks

Validation will now be performed on your model instance, to check it, you do:
ModelState.IsValid
In the controller method prior to the save operation. As long as the input names on the view correspond with your model class's property names, binding and validation will be performed implicitly prior to your action method being executed. To show your validation messages in your view, add a Html.ValidationMessage() to the top of the view. Hope this helps. By the way its well worth checking out Foolproof Validation which provides conditional validation attributes and some other good stuff.

Better practice would be use seperate model and viewmodel. Convert your model to viewmodel and then pass it to view
public ActionResult Edit(int id)
{
var movie = this.connection.MovieContext.SingleOrDefault(m => m.ID == id);
var vm = new MovieCreateViewModel{ Id = movie.Id};
return View(vm);
}
//
// POST: /Movie/Edit/5
[HttpPost]
public ActionResult Edit(MovieCreateViewModel vm)
{
try
{
if (ModelState.IsValid)
{
var movie = new Movie{Id = vm.Id};
this.connection.MovieContext.Attach(movie);
this.connection.MovieContext.Context.SaveChanges();
return RedirectToAction("Index");
}
}
catch
{
return View(movieedit);
}
}

Related

How can I send id to controller action method in ASP.NET MVC?

I am working a project and I had some trouble. I want to send id from html beginform but I couldn't do it.
I want to send /BuyTourTicket/tourid
This is my code:
public ActionResult TourTicket(int id)
{
var tour = db.TBLTUR.Find(id);
ViewBag.tourid = tour.id;
ViewBag.tourname = tour.tur_basligi.ToString();
ViewBag.kalkisYeri = tour.kalkis_yeri.ToString();
ViewBag.tarih = tour.tarih.ToString();
ViewBag.detaylar = tour.detay.ToString();
ViewBag.turYetkilisi = db.TBLTURYETKILISI.Find(id).ad + " " + db.TBLTURYETKILISI.Find(id).soyad;
return View("TourTicket",tour);
}
public ActionResult BuyTourTicket()
{
return View();
}
[HttpPost]
public ActionResult BuyTourTicket(int id)
{
TBLTURREZERVASYON reservation = new TBLTURREZERVASYON();
reservation.tur = id;
db.TBLTURREZERVASYON.Add(reservation);
db.SaveChanges();
return View();
}
This is the error I get:
The first, the default route usually describes the id parameter as optional. Therefore change the action method declaration to public ActionResult BuyTourTicket(int? id):
[HttpPost]
public ActionResult BuyTourTicket(int? id)
{
TBLTURREZERVASYON reservation = new TBLTURREZERVASYON();
reservation.tur = id;
db.TBLTURREZERVASYON.Add(reservation);
db.SaveChanges();
return View();
}
The second, change the parameters order in the Html.BeginForm() of the TourTicket.cshtml to:
#using (Html.BeginForm("BuyTourTicket", "Tur", new { id = ViewBag.tourid }, FormMethod.Post))
The route values are third parameter and the HTTP method is the fourth parameter.
I would fix an action route
[HttpPost("{id"})]
public ActionResult BuyTourTicket(int id)
and add Get to another action
[HttGet]
public ActionResult BuyTourTicket()
{
return View();
}

How to call a asp.net mvc action without changing the url

I have a simple controller with 2 custom actions. From the index view there is a link to the action "MyActionA" with id = 3. Then the matching view is returned.
On the view "MyActionA" there is a link (on a submit form button) to the action "HiddenAction".
The action "HiddenAction" only updates a property on given model. I do not want to change the URL on client browser. But I want to send the updated model to the client.
I tried it with Redirect but it never works.
Has anyone an idea?
Here is the controller code:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult MyActionA(int id)
{
if (id <= 0) throw new ArgumentException();
HomeModel model = GetModel();
return View(model);
}
[HttpPost]
public IActionResult HiddenAction(HomeModel model)
{
if (model == null) throw new ArgumentNullException(nameof(model));
model.MyPropB = 999;
//HttpContext.Response.Redirect()
return View(model);
//return Rewrite("MyAtionA/3");
//return RedirectToAction(nameof(MyActionA), 3);
//return View();
}
// Helper
private HomeModel GetModel()
{
return new HomeModel();
}
public class HomeModel
{
public int MyPropA { get; set; }
public int MyPropB { get; set; }
}
}
You would have to use AJAX to post the data back to the server (i.e. make the request client-side via JavaScript). Any other method (such as an HTML form) or a link will cause the URL in the browser to change.

asp.net mvc4 two differend views for one action

I need two differend views for Kaminy/KaminniTopky & Kaminy/KaminniTopky/5.
How can I do it in that way?
public class KaminyController : Controller
{
//
// GET: /Kaminy/
public ActionResult Index()
{
return View();
}
// GET: /Kaminy/KaminniTopky
public ActionResult KaminniTopky()
{
return View();
}
// GET: /Kaminy/KaminniTopky/5
public ActionResult KaminniTopky(int id)
{
return View();
}
}
#Stephen Muecke's idea has merit, you can combine as:
public ActionResult KaminniTopky(int? id)
{
if (!id.HasValue)
{
return View();
}
else
{
return View("OtherViewName");
}
}
There are overloads that take the model too - return View(someModel); and return View("OtherViewName", someModel); respectively.
In MVC 5 you could:
[Route("Kaminy/KaminniTopky")]
public ActionResult KaminniTopky()
{
return View();
}
[Route("Kaminy/KaminniTopky/{id}")]
public ActionResult KaminniTopky(int id)
{
return View("OtherViewName");
}
For something like /Kaminy/KaminniTopky/KaminniTopkyWithOther/5 you would use routing rather than a weird controller structure to support other style URLs.
E.g. In RouteConfig:
routes.MapRoute(
"SomeRoute",
"/Kaminy/KaminniTopky/KaminniTopkyWithOther/{id}",
new { controller = "Kaminy", action = "KaminniTopkyWithOther", id = "" }
);
Make sure this comes before the default route.
Then it doesn't matter what your action is called as long as its the same as defined in the route.
public ActionResult KaminniTopkyWithOther(int id)
{
return View("OtherViewName");
}

How to get the return value of controller method?

In MVC4, I am trying to use the one controller method in another controller method using RedirectToAction but it shows error while try to receive the returned value of other controller's method.
I have following controller method:
public class TranslationController : Controller
{
public ActionResult Search_Query()
{
List<Surah> Records = new List<Surah>();
Records = RedirectToAction(" Load_Surahs", "Surah_CRUD");
...
return Json(new { key = Records }, JsonRequestBehavior.AllowGet);
}
}
Another controller method:
public class Surah_CRUDController : Controller
{
public ActionResult Load_Surahs()
{
List<Surah> Records = new List<Surah>();
...
return Json(new { key = Records }, JsonRequestBehavior.AllowGet);
}
}
how to fix it, i mean i want to use Load_Surahs returned list of objects in Search_Query method...
Place method GetSurah in separate service.And use this service in both controllers.
public class TranslationController : Controller
{
public ActionResult Search_Query()
{
List<Surah> Records = someService.GetSurah();
...
return Json(new { key = Records }, JsonRequestBehavior.AllowGet);
}
}
public class Surah_CRUDController : Controller
{
public ActionResult Load_Surahs()
{
List<Surah> Records = someService.GetSurah();
...
return Json(new { key = Records }, JsonRequestBehavior.AllowGet);
}
}
Change the code to:
public ActionResult Load_Surahs()
{
List<Surah> Records = new List<Surah>();
...
return RedirectToaction("Search_Query","TranslationController ",
new {jsData = "Your Json data here" });
}
And in your other action use
public ActionResult Search_Query(Json jsData)
{
}
Change the return type of Load_Surahs() to JsonResult

mvc3 RedirectToAction

Why isn't this working. It keeps telling me edit needs a EditStudyModel when I redirect in my Create method. A Redirect should do a get, right?
public ViewResult Create()
{
var createStudyModel = new CreateStudyModel();
return View(createStudyModel);
}
[HttpPost]
public ActionResult Create(CreateStudyModel createStudyModel)
{
try
{
//TODO: Send CreateStudyCommand
return RedirectToAction("Edit", new { scientificStudyId = new Guid("{1C965285-788A-4B67-9894-3D0D46949F11}") });
}
catch
{
return View(createStudyModel);
}
}
[GET("ScientificStudy/Create/{scientificStudyId}")]
public ActionResult Edit(Guid scientificStudyId)
{
//TODO: Query real model
var model = new EditStudyModel() {StudyNr = "T01", StudyName = "Test"};
return View(model);
}
[HttpPost]
public ActionResult Edit(EditStudyModel editStudyModel)
{
try
{
//TODO: Send UpdateStudyCommand
return RedirectToAction(""); //TODO: Terug naar Studie lijst
}
catch
{
return View(editStudyModel);
}
}
You're returning a redirect with a URL as a string, the controller isn't able to parse the GUID and convert it back to a guid object, so it's not able to resolve the correct method signature to use. Change it to:
return RedirectToAction("Edit", new { scientificStudyId = "{1C965285-788A-4B67-9894-3D0D46949F11}" });
and
public ActionResult Edit(string scientificStudyId)
I found the issue. I copy paste my create.cshtml to edit.cshtml Forgot to change the first line:
#model Website.Models.CreateStudyModel --> to --> #model Website.Models.EditStudyModel

Categories