MVC Linking to views - asp.net-mvc

New to MVC so learning (in a frustrated kind of way as finding simple things that used to take 5 minutes in webforms have become over complicated)
So I've set up a solution in VS2015 which comes with the pre-requisite Account section.
I've also set up tables in a database and built the entities from that (producing some CRUD)
So I can log in and get to my AccountHome view (return View("AccountHome") in the AccountController)
From my AccountHome page, I can navigate to another view using a seperate controller(#Html.ActionLink("Add Foods", "Create", "fad_userFoods", new { id = ViewBag.userID }, new { #class = "btn btn-default" }))
Here I do some form entry and the data is successfully added to the database but here is where my problem lies. After data entry I want to go back to the AccountHome view
So in my fad_userFoodsControler I have this code(return RedirectToAction("AccountHome","Account")) - says resource cannot be found!!!
In my AccountController I have the following code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AccountHome()
{
return View();
}
In my AccountViewModels I have this code:
public class AccountHomeViewModel
{
public string Email { get; set; }
}
Finally, in my AccountHome.cshtml page I have this declared at the top (#model FiveADayMVC2.Models.AccountHomeViewModel)
Where am I going wrong? Looked at numerous posts and they all do it this way. I know the view exists because I can get to it from login. Yet, if I type the url manually (i.e. my url followed by /Account/AccountHome) it's not found either???
It's going to be a lack of understanding on my part but where?
Thanks in advance for any pointers

Try using RedirectToAction This will navigate the user to the view of a specific action in a given controller.
if(actionSuccess)
{
return RedirectToAction("Index", "Home");
}
UPDATE:
Make sure you have a controller for HttpGet
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AccountHome()
{
return View();
}
public ActionResult AccountHome()
{
return View();
}
Since you added [HttpPost] to the controller it will be the one executed after a post was made on "AccountHome"

Related

return RedirectToAction("Edit", Model)

Afternoon Folks,
I have a question in reference to how to redirect to another model within my mvc project.
I have a controller with CRUD operations, and i have a [HttpPost] action on Create. The system saves the data to the database as required but instead of me sending the user back to the "Index" page i want to sent them to another model.
I know how to use the redirect option...
// POST: CarerDetailsNew/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CarerViewModel carerViewModel)
{
if (ModelState.IsValid)
{
db.CarerDetails.Add(carerViewModel.carer);
db.SaveChanges();
return RedirectToAction("Edit", carerViewModel.carer);
//return RedirectToRoute("ClientRecordsController");
}
return View(carerViewModel);
}
However i have read that i may be able to use the "RedirectToRoute" option to get back to another model.
The model that i am in is my "Carer" model but i want to get back to my "Client" model and specifically the "Edit".
I have tried to replace my RedirectToAction to one of the following but this fails to see the "Client" model.
return RedirectToRoute("Edit", clientViewRecord.client);
Or
return RedirectToRoute(ClientRecordsController, "Edit", clientViewRecord.client);
Any suggestions are more than welcome as i am struggling to get this to work.
Regards
Betty

SurfaceController generate incorrect URL?

A Form is posted to a SurfaceController 'Submit' action. After saving to the database, it redirects to another action 'LeadContact', in the same controller (using RedirectToAction()), passing in 'Id' as a paramter. The model is then populated and passed to the 'LeadContact' view.
Not sure if I'm doing this correctly, but when 'LeadContact' renders in the browser, the URL shows as
http://localhost:50656/umbraco/Surface/HealthInsurance/LeadContact?leadOptionId=70`
while I'm expecting it to be
http://localhost:50656/HealthInsurance/LeadContact?leadOptionId=70
In short it adds /umbraco/SurfaceContact' into url.
Can you please advise how I can correct it and what I'm doing wrong ?
public ActionResult Submit(FormCollection form)
{
//Some logic and later redirect to another action 'LeadContact'
return RedirectToAction("LeadContact", new { leadOptionId = _id});
}
public ActionResult LeadContact(int leadOptionId)
{
MyViewModel model = new MyViewModel();
//Lines of code to populate data into model
return View("LeadContact", model);
}
Thanks for your help and sharing.
Check your project properties, under Web you most likely have a virtual path specified.

Resource Cannot Be Found Error on Using "HttpPost" in Controller

Hello Am Working on a ASP.Net MVC 3 project and am getting a error called "Resource cannot be found" My situation is i have
1: am Using my own views and returning them in actions for instance i created a view manually first called "Create.cshtml" and manually added it to a action like this
[HttpPost]
Public ActionResult CreateStudent(StudentIfo studentinfo)
{
db.StudentInfo.add(studentinfo);
db.SaveChanges();
Return View("~/Views/Student/Create.cshtml");
}
[HttpGet] Before this Action works good but why Not HttpPost???
My Route Map says:
routes.MapRoute(" ",
"{controller}/{action}/{id}",
new { controller = "Student", action = "CreateStudent", id = UrlParameter.Optional }
);
2: Whenever i write [HttpPost] i get this Error and if I remove it then everything works good if such thing continues then how to save the data??
3: My Create.cshtml has a #Html.BeginForm("CreateStudent","Student",FormMethod.Post) am not getting what the issue is?? i have searched a lot but not getting a good answer.
4: What is best way for CURD operation when we are using our own views rather using Visual studios Scaffolding templates i.e am I going in right way?? i want my own views and then write my controllers according to them not as that of Visual Studio way first write controller then right click "Add-View"
Please recommend some good ways or any site or tutorials regarding it.
In short you will need both, you need a [HttpGet] action to return the initial form that the user can enter values into and then a [HttpPost] version to do the persistence. From this [HttpPost] method you should then RedirectToAction (return RedirectToAction(...)) to ensure that reloading of the page does not re-run the post operation.
So:
[HttpGet]
public ActionResult CreateStudent()
{
var viewModel = new CreateStudentViewModel { /* Set properties here or load data for it */ };
return View(viewModel);
}
[HttpPost]
public ActionResult CreateStudent(PostedValues values)
{
if (ModelState.IsValid)
{
// Create Student Here
return RedirectToAction(/* Jump to a logical place with a Get */)
}
/* Initialize correct error viewModel again and show the create student screen with validation errors */
return View(viewModel)
}
Personally I name these methods GetCreateStudent and PostCreateStudent and add two routes with a route constraint that limits the Http Method (see here)

MVC3 RenderPartial caching across multiple pages

Can anyone tell me if its possible to Cache a RenderPartial across multiple pages? I have a RenderPartial for a user profile that shouldn't really ever change unless the user updates their profile. So i dont really want to go back and get his/her profile every time i load a page. I would much rather pass the partial around until im forced to update (i.e. profile update)
I looked at the DonutHole example that p.haack put together, but it seems to be relevant for a single page. Can someone point me in the right direction or offer any advice? Or am i only able to cache one page at a time? thanks!
You could use RenderAction instead. Example:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
[OutputCache(Duration = 6000, VaryByParam = "none")]
public ActionResult Cached()
{
// You could return whatever you want here, even a view
// but for the purpose of the demonstration I am simply
// returning a dynamic string value
return Content(DateTime.Now.ToLongTimeString(), "text/html");
}
}
and inside the Index.cshtml and About.cshtml views you could include the child action:
<div>
#{Html.RenderAction("Cached");}
</div>
and it you will get the cached version of it in both pages.

Get and post methods with different names

I am using ASP.NET MVC 3.
I have an action method called New. When form validation succeeds then I want Create to handle the request.
public ActionResult New()
{
// Code
}
[HttpPost]
public ActionResult Create()
{
// Code
}
I have 2 questions regarding this. Firstly, how do I modify my Html.BeginForm to handle the above? I tried the following but I get an error, it is looking for the physical file Create (News is my controller name):
#using (Html.BeginForm("Create", "News"))
{
<!-- Code -->
}
Secondly, how do I prevent a user from typing in /News/Create in the URL. Create should handle only my post requests coming from New.
UPDATE:
I managed to get something working. The original URL looks like this:
http://localhost:33947/News/New
After I click the submit button and validation fails then the URL looks like:
http://localhost:33947/News/Create
Why does it do this? I want it to stay:
http://localhost:33947/News/New
Here is my action method code:
public ActionResult New()
{
return View();
}
[HttpPost]
public ActionResult Create(NewsViewModel newsViewModel)
{
if (!ModelState.IsValid)
{
return View("New", newsViewModel);
}
return View("Index");
}
#using (Html.BeginForm("Create", "News", FormMethod.Post))
You cannot prevent user from typing address manually, but you can add another Create action marked with [HttpGet] attribute which will show user the error page. Anyway, your current Create action method will not handle such requests. Probably user will get standard File not found error in this case.
UPDATE: Html.BeginForm("Create", "News") means to submit the form to action "Create" of the controller "News", so it works as it should. If you want to submit to /News/New, replace it with Html.BeginForm("New", "News").
Regarding your second question, instead of:
if (!ModelState.IsValid)
{
return View("New", newsViewModel);
}
you should use :
if (!ModelState.IsValid)
{
return RedirectToAction("new");
}
Now this has the undesired side affect that your Modelstate is lost. (no validation errors are shown in your form.
To fix this add the ModelStateToTempData attribute to both your new and create action.
This attribute come as part of http://mvccontrib.codeplex.com/ .

Resources