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
Related
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();
}
I have a problem with my project. When I enter data without making a mistake, the data is correctly registered in my database, but when I want to register empty data and field validation is activated with Data Annotatios, the flow continues towards the next view but no information is registered. How could I solve it?
Controller:
[HttpGet]
public ActionResult RegistroSolicitudes(int idprof)
{
ViewBag.idprof = idprof;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RegistroSolicitudes(TB_Solicitudes s, int id)
{
try
{
if (ModelState.IsValid)
{
db.SP_REGISTRO_SOLICITUDES(s.TITULOSOL, s .NOMBRE, s.APELLIDO, s.CELULAR, s .DISTRITO, s.DESCRIPCI, s.IDPROFESI,.IDCLIENTE, s.ESTADO);
return RedirectToAction ("ListadoSolicitudesPorUsuario",
new { id = id });
}
}
catch
{
return View();
}
return View();
}
In the view I am using this code to activate only the POST method:
#Html.ActionLink("Registrar Solicitud", "RegistroSolicitudes",
new { id = #Session["IDUSUARIO"] },
new { #class = "btn btn-primary",
#onclick = "$(this).parents('form').attr('action', $(this).attr('href'));$(this).parents('form').submit();return false;" })
I am working with adding a new MVC page and have the method and calls up and running. My issue is that I am not wanting to pass in URL parameters to show in my page but need to pass in the parameters for the method when I do a redirect to my new page. Currently I have it set up like this:
Page.cs
void ToNewPage()
{
Response.RedirectToRoute(new { controller = "ControllerName", action = "ActionName", ID1 = 1, ID2 = 2 });
}
ControllerName.cs
public ActionResult ActionName(int ID1, int ID2)
{
...
return View(model);
}
Currently with my code I get the URL ~/ControllerName/ActionName?ID1=1&ID2=2. I am just wanting the URL to just be ~/ControllerName/ActionName. I know this would be easier on a frontend or maybe through javascript but needing to do this from the ToNewPage method if possible.
There are working codes:
PageController.cs
public class PageController : Controller
{
// GET: Page
public ActionResult Index()
{
return View();
}
public ActionResult ToNewPage()
{
var ids = Newtonsoft.Json.JsonConvert.SerializeObject(new { ID1 = 1, ID2= 2 });
TempData["ids"] = ids;
return RedirectToAction("Index", "NewPage");
}
}
NewPageController.cs
public class NewPageController : Controller
{
// GET: NewPage
public ActionResult Index()
{
if (TempData["ids"] != null)
{
dynamic ids = JsonConvert.DeserializeObject(TempData["ids"] as string);
ViewBag.ID1 = ids.ID1;
ViewBag.ID2 = ids.ID2;
}
return View();
}
}
NewPage\Index.cshtml
#{
ViewBag.Title = "Index";
}
<h2>NewPage</h2>
<ul>
<li>ID1: #ViewBag.ID1</li>
<li>ID2: #ViewBag.ID2</li>
</ul>
You should use TempData:
void ToNewPage()
{
TempData["ID1"]="ID1 Value"
TempData["ID2"]="ID2 Value"
Response.RedirectToRoute(new { controller = "ControllerName", action = "ActionName"
});
}
public ActionResult ActionName()
{
int ID1=int.parse(TempData["ID1"].ToString());
int ID2=int.parse(TempData["ID2"].ToString());
return View();
}
You can fill many TempDatas in many controllers and use them in many Views and controllers
I want to be able to use the value of a string variable passed to one ActionResult, within another ActionResult.. How could i go about doing this?
public ActionResult PassCategoryPlaceHolder(string placeHolder)
{
var result = placeHolder;
return RedirectToAction("EditCategory", result);
}
I want to be able to use 'result' in my other ActionResult as follows:
public ActionResult EditCategory()
{
ViewBag.Message = Convert.ToString(result);
return View();
}
Note: I am trying to avoid sending 'placeHolder' directly to the ActionResult where i need it.
You can do something like this
public ActionResult PassCategoryPlaceHolder(string placeHolder)
{
var result = placeHolder;
return RedirectToAction("EditCategory", new { message = result});
}
And in other method:-
public ActionResult EditCategory(string message)
{
var model = new EditCategoryViewModel();
model.Message = message;
return View(model);
}
Simply use a Session variable:
public ActionResult PassCategoryPlaceHolder(string placeHolder)
{
Session["result"] = placeHolder;
return RedirectToAction("EditCategory");
}
public ActionResult EditCategory()
{
var Message = Convert.ToString(Session["result"]);
return View();
}
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);
}
}