How can I check the HTTP response from inside a MVC controller? - asp.net-mvc

I have:
[HttpPost]
public ActionResult Create(EditViewModel viewModel)
{
...
}
I know I can check the viewModel object when debugging but how can I get the actual HTTP response from within the controller at the "..." point?
Also how can I see the data that gets bound to the viewModel (without looking at the viewModel). Where's that data stored in the Response object?

If you add FormCollection as a parameter to your POST action method, MVC will populate it with the posted form data. Or through the Form property of the Request
[HttpPost]
public ActionResult Create(EditViewModel viewModel, FormCollection formCollection)
{
var name = formCollection["name"];
var email = Request.Form["email"];
}
But modifying it inside the controller violates the whole "MVC" pattern.

Related

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.

MVC Model Updating

I have a Model which is a business layer class and I pass that to the view through the controller in the following manner:
public ActionResult Edit(int id)
{
var MyModel = MyDatabaseInstance.Listings.GetByID(id);
return View(MyModel);
}
In the control for the update I have the following:
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
What I really want is to be able to get back the model object that I have used during the initial binding. Is that possible? If I change the arguments of the edit as such:
public ActionResult Edit(Listing MyModel)
it complains that there is "No parameterless constructor defined for this object." and my model cannot have a parameterless constructor.
I would suggest that you use a ViewModel rather than binding directly to the entity from your database.
Using a ViewModel has the following advantages (not exhaustive).
Views often have specific requirements to how you display data. If you use the model from your DB then your going to endup adding unnecessary properties to your model.
Security, you don't want to expose properties on your model to automatic binding when posting back to the controller.
Validation requirements may be different for your view than your entity model.
Just easier to change a ViewModel if your presentation requirements change.

Process get and post

I have an question about the get and post process in ASP.NET MVC 4.
I'm sure that often talk about but it isn't easy to search for this topic.
Let me try to explain:
I start my controller with the standard method:
[HttpGet]
public ActionResult Item()
So, in this function I retrieve a lot of important data as example the user id and so on.
In my case, I even collect data in my viewbag() to decide if a form has to be displayed or not.
Now, if I start a post back:
[HttpPost]
public ActionResult Item(FormCollection formCollection)
the function gives as standard View() back.
The Problem is now, that after the post method, the business logic (retrieve user id and so on) of the GET method isn't called... I have tried to solve it with
return this.RedirectToAction("Item");
but is that really the solution for repeat the logic out of the start (get)? And how can I give the new values from the post method to the get method?
Best regards,
Patrik
That pattern is called Post/Redirect/Get.
To pass additional data to GET method you can use TempData and ModelStateToTempDataAttribute from MvcContrib - it passing ModelState to tempdata if Redirect is returned and tempdata to modelstate if View is returned.
[HttpGet]
[ModelStateToTempData]
public ActionResult Item(int id)
{
// prepare view
return View();
}
[HttpPost]
[ModelStateToTempData]
public ActionResult Item(FormCollection formCollection)
{
// do some business logic
int id = service.DoBusinessLogicAndReturnSomeId();
return this.RedirectToAction("Item", new { id });
}
You should avoid to have business logic in GET. All business logic should be inside POST method and after you invoke that you can redirect to GET where you prepare your view.

MVC sending data from View to Controller

I am quite new to MVC 3.
I know how to send a strongly typed object from a Controller to a View. What I have now, is a View which contains a table/form which consists of that data.
The user can change that data whilst they're are in that View (html page).
When they click on "Save", how do I send the data from the View back to the Controller so that I can update my database.
Do I overload the Controller method so that it accepts a parameter of the model type? Can you please provide some source code.
(Please do not show code of persisting data to a database, I know how to do that part).
Thank you very much for helping me.
I would also prefer using #Html.BeginForm()
I like creating an action method made for my post data. So let's say you have a UserViewModel:
public class UserViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
Then a UserController:
public class UserController
{
[HttpGet]
public ActionResult Edit(int id)
{
// Create your UserViewModel with the passed in Id. Get stuff from the db, etc...
var userViewModel = new UserViewModel();
// ...
return View(userViewModel);
}
[HttpPost]
public ActionResult Edit(UserViewModel userViewModel)
{
// This is the post method. MVC will bind the data from your
// view's form and put that data in the UserViewModel that is sent
// to this method.
// Validate the data and save to the database.
// Redirect to where the user needs to be.
}
}
I'm assuming you have a form in your view already. You'll want to make sure that the form posts the data to the correct action method. In my example, you'd create the form like so:
#model UserViewModel
#using (Html.BeginForm("Edit", "User", FormMethod.Post))
{
#Html.TextBoxFor(m => m.Name)
#Html.HiddenFor(m => m.Id)
}
The key to all this is the model binding that MVC does. Make use of the HTML helpers, like the Html.TextBoxFor I used. Also, you'll notice the top line of the view code I added. The #model tells the view you'll be sending it a UserViewModel. Let the engine do work for you.
Edit: Good call, did that all in Notepad, forgot a HiddenFor for the Id!
In MVC, the act of scraping out data from POST or GET HttpRequests is referred to as Model Binding - there are plenty of SO questions relating to this.
Out of the box, MVC will bind your Get and Post variables based on convention, e.g. a form field with the name 'FormName' will be bound back to a parameter on your controller with the same name.
Model binding also works for objects - MVC will instantiate an object for your controller, and set the properties with the same name as your form.

ASP.NET MVC, JSON post to controller action with FormCollection parameter

I have a bunch of controller actions mostly used for saving data to backend storage. For now most of them use a signature like this:
//
// POST: /WidgetZone/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
as you can see, it accepts FormCollection. This works fine with classic user views. Now I want to JSON- enable these actions. And I do it using JsonPox action filter like this:
//
// POST: /WidgetZone/Create
[JsonPox]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
Will this work when the action expects FormCollection?
For instance this work without issues (of course I construct Json object in my JavaScript client-side to pass it into this action):
//
// POST: /WidgetZone/Create
[JsonPox]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(string id, string description)
It is all about a task of converting postback UI into asynchronous one, so that saves and updates would be done async. Am I on the right track? I do think that developing separate Json, XML or classic ViewResult actions is not the best way to go.
Help appreciated
This filter is based on the the OnActionExecuted method which is run after the action method is executed in order to JSON or XML serialize the returned model. What you have as input to your action method is not important. Once the action finishes execution the filter will look for the model that you stored in the ViewResult and serialize it according to the Content-Type header that's passed in the request.

Resources