What is the right way to handle $_POST data in MVC?
The best option is to use #2 approach, with some alterations.
I would write it as something like this:
public function postLogin( $request )
{
$service = $this->serviceFactory->build('Recognition');
$service->authenticate( $request->getParam('username'),
$request->getParam('password') );
}
// Yes, that's the whole method
There is no need to actually create variables, if you have used something like a Request
instance to abstract the user's input.
Also, you might want to replace the
Request::getParam()
method with something likeRequest::getPost()
- although I have come to the conclusion that, in a correctly structured application, theGET
andPOST
parameters should not share same name.
The serviceFactory
which you see in the code snippet would be an object that you inject in both controller and view instance. It would let you share same service instances between controllers and views.
It is responsible for creation of services (which would contain the application logic, while leaving the domain business logic in the domain objects), which helps you isolate the interaction between domain entities and storage abstractions from the presentation layer.
About the other options:
The Controller only calls the Model and the Model handle the $_POST data.
In the MVC and MVC-inspired design patterns the model should be aware of neither the user interface nor of the presentation layer as whole. The
$_POST
variable in PHP is a superglobal.If you use it with model layer, your code becomes bound to the web interface and even the specific request method.
The Controller transforms $_POST data into a Model's object and only pass the object to Model
Not entirely sure what you meant with this. Seems you were talking about instantiation of an abstraction, which would contain the user's request. But in this case controller becomes responsible for instantiation/creation of said structure, which would violate SRP.
Closing notes:
One thing you must understand is that, in context of web based MVC applications, the User of your application is the browser. Not you. Browser sends the request, which is handled by routing mechanism and disseminated by controller. And view produces the response to your browser.
And the other thing is: Model is neither a class nor an object. Model is a layer.
Update
Generally, the same Controller handles request from a browser, a web service, an offline application, etc, or each one has it own Controller?
You should be able to have single controller, that deals with all the forms of application. But that is only on the condition, you are actually using same application for all 3 use-cases.
To do so there are two conditions:
- you need to abstract the
Request
instance, that controller receives - the view should be instantiated outside the controller
This way you can have one application to fulfill all the requirements. Only thing, that each variant has different, is the bootstrap stage, where you create the Request
instance and select the proper view.
In the situation, that you described, the changing part would actually be the view, since a REST or SOAP service would be expected to produce a different response than an ordinary web application.
How to get POST data from request asp mvc 5
You can just use a model as a parameter; most of the time ASP.Net MVC's Default ModelBinder can map to your model.
$.ajax({
url: "@Url.Action("UploadImageCallback", "Cabinet")", // If you want strongly-typed URL
contentType: "application/json; charset=utf-8",
method: "POST",
data: JSON.stringify(data)
...
});
public class CustomerModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
[HttpPost]
public ActionResult UploadImageCallback(CustomerModel model)
{
// Do something
}
POST data to controller with ASP.NET MVC
Try replacing your code with the following:
@using (Html.BeginForm("FiEdit", "EditConfig", FormMethod.Post))
{
<div class="form-group">
<label for="issuerKey">Issuer Key</label>
<input type="text" name="key" />
<input type="submit" class="btn btn-default" value="Search" />
</div>
}
This will POST the parameter key
to the EditConfig controller.
If you'd like to post to the action TestEdit in another controller, say the TestController, your code should be changed to the following:
@using (Html.BeginForm("TestEdit", "Test", FormMethod.Post))
...
To resolve the "model item passed into the dictionary" error, change your POST to be this:
[HttpPost]
public ActionResult FiEdit(int key)
{
return View(new IssuerKey() { Key = key });
}
How to pass $_POST to models in php mvc
The Model is a layer. First, you need to understand what goes on in the model layer, and you can read about that here.
Now we've got that cleared up, let's address your question. You want to pass data from your view to some sort of service / data mapper in your model layer. This is handled the same as every other request.
- Perform a request to your application
- Routing handles sending this request to the appropriate controller
- You may have some sort of mechanism to allow XMLHttpRequests only to certain controllers / methods. If so, somewhere around your routing you should perform your checks for this.
- Your model layer (maybe a validation service) validates the post data and makes sure it's what you're expecting. I have, in the past, made sure only certain keys / values exist within the post array.
- Pass this data to a service in the model layer, which then uses it as you see fit.
Basically, treat $_POST
requests the same as any other request, just check (using either your own or framework built-in methods) that it's the request type and content you require, then use it as normal.
As for your "a lot of fields", and you're worried about code re-usability / not having to repeat yourself, get the data you require from the client-side using a loop (perhaps via the class using JavaScript). Then, if you add any more data in the future, the loop will automatically pick it up and send it over for you.
Think a little more abstract in your model, i.e. it'll be able to handle the loop's input, and you're golden.
How receive data from POST in asp.net MVC
When your are posting data to method in C# you need to have class defined with same parameters in your post method.
In your case your method will become
[HttpPost]
public ActionResult save(Person person)
{
//Here your need to access person object to get the data
string name = person.name;
return Json(name, JsonRequestBehavior.AllowGet);
}
Now class person will be representation of what your sending from your client.
Again in your case Person class will be like
class Person
{
public int ID {get; set;}
public string name {get; set;}
public string lastname {get; set;}
}
So as mentioned in comments creating class Person
in completely optional and you can skip that it just on of best practice. In that case your post method will look like
[HttpPost]
public ActionResult save(Object person)
{
//Here your need to access person object to get the data
string name = person.name;
return Json(name, JsonRequestBehavior.AllowGet);
}
Related Topics
Laravel Add a New Column to Existing Table in a Migration
How to Get Wkhtmltopdf to Execute via PHP
Php/Regex: How to Get the String Value of HTML Tag
Directory Index Forbidden by Options Directive
PHP Pdo::Bindparam() Data Types.. How Does It Work
Is It Ever Ok to Store Password in Plain Text in a PHP Variable or PHP Constant
Php: How to Sort the Characters in a String
Codeigniter, Result() VS. Result_Array()
How to Store and Retrieve Image Contents from the Database Using Laravel
Best Way to Allow Plugins for a PHP Application
PHP Sessions with Disabled Cookies, Does It Work
What Factors Make PHP Unicode-Incompatible