I have an MVC application. Say for example if we have a dropdown Cars makes which when selected posts to itself and gets Car Models. Now on post, the field Car makes loses it value. I am using Form.Get("combo_box_field_name") and if it has a value I am prepopulating the car make dropdown. As lot of controls on my form do this sort of post and i have to prepopulate the fields , I was wondering if this is the right way of doing stuff. I have done loads of asp classic works and also asp.net and looks like mvc is very similar in approach tp classic asp. If someone can guide in in the right way this can be handled it would be greatly appreciated.
I am not looking to use AJAX so pls dont tell me with regard to cascading dropdowns and I have a host of other controls in the form which will need updating on the form being posted to itself before I leave the page to save the data
I don't think I've ever used Form.get in my MVC application.
I post back to the controller which looks like;
[AcceptVerbs(HttpVerbs.Post), Authorize]
public ActionResult MyAction(FormCollection collection)
{
MyClass myClass = new MyClass();
UpdateModel(myClass);
//do stuff with data
return View(myClass);
}
So basically you're letting MVC grab the data from the view for you.
You may need to reload your dropdown lists with this but you can get around that by using JSON to do partial postbacks.
Related
Not sure if this question has already been asked.
I am developing an ASP .NET MVC 2 site. My view has a drop down where user can select which record to display for editing. When this drop down is changed, the field values for the currently selected record automatically get posted to the server and are saved in the session. In the response the server then returns a view for editing the newly selected record.
The problem I am having is that some of the field values from the previous record are being remembered when the new record is displayed.
In my view I have something like the following which is causing the problem:
<%= Html.TextBox("ActionTypeDetails.DisplayName",
Model.ActionTypeDetails.DisplayName) %>
Here I want the posted data to populate a parameter called ActionTypeDetails which has multiple properties including DisplayName.
My controller actions looks something like this:
public ActionResult EditActionType(Guid PluginEditID,
Guid? SelectedActionTypeID,
ActionTypeViewObj ActionTypeDetails)
I have tried changing my view to this:
<%= Html.TextBox("PostedActionTypeDetails.DisplayName",
Model.ActionTypeDetails.DisplayName) %>
And my controller action to this:
public ActionResult EditActionType(Guid PluginEditID,
Guid? SelectedActionTypeID,
ActionTypeViewObj PostedActionTypeDetails)
Yet it still exhibits the same problem. Can someone please explain the logic to why it works like this? What is the easiest workaround that would still allow me to use the built in model binding? I know I can clear the ModelState but this is not ideal as I want some of the other data on the form to be remembered.
If you post back to the same url, asp.net has mechanisms which preserve field values. More info can be found here.
I'm new to mvc, mvp or whatever you want to call them. Right now I try to implement a ReservationController where the user first selects a date and then gets a list of suitable time suggestions. As you should know, the suggestions depend on the selected date. This is where my problem / question starts. Should I:
1) Put an event in the View interface like DateChanged and then subscribe to it in the controller?
2) Call UpdateSuggestions on the controller from my asp page, when the selected date changes. (then I must make the controller method public)
Or
3) Update the suggestions in the constructor of the controller.
Regards and thx for help
eric
You need to get out of the control events mind-frame which drives ASP.NET web forms. Although it is technically possible to accomplish things this way I would suggest going down a different route.
You need to return a view to the user which lets them enter a date into a form. They then post the form back to the server and another action method handles this post. This method gets the list of time suggestions and returns a view with these times as its model.
Take a look here for some decent videos on MVC basics: http://www.asp.net/mvc
Here's some great examples of ASP.Net MVC that are great reading for anyone just getting started.
http://www.asp.net/mvc
http://www.asp.net/mvc/tutorials/getting-started-with-mvc3-part1-cs
These two samples include books that take you step by step through creating an MVC project:
http://nerddinner.codeplex.com/
http://www.asp.net/mvc/samples/mvc-music-store
This may not answer your question directly BUT going throught these samples should help make it clear how MVC works and specifically how to use it in ASP.Net. :-)
Here's also a little background on the MVC pattern.
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
http://msdn.microsoft.com/en-us/library/ff649643.aspx
You should put a link or form in your view that points to a URL that passes the date to an action in the controller.
This action should take the date as a parameter, fetch the data for that date, and pass it to a separate view that renders the data.
You should learn the basics of HTTP and web pages, as well as the underlying design of ASP.Net MVC.
Writing code in a framework or system that you don't understand is a recipe for frustration and disaster.
Sorry but your knowledge in asp.net mvc is very very poor. Better to get some knowledge better, or you cannot make it work. But anyways
1) There do not exist events in views in mvc
2) View does not call contstructor on controller
3) see first two
I think your are misunderstanding how MVC works.
If you are not clear on how MVC works it would be worth checking out something like nerd dinner and Scott Gu's blog.
You could have your dates link to an action like below to process this:
[HttpGet]
public ActionResult YourAction(DateTime date)
{
// Add action logic here
Manager suggestions = new Manager();
var suggestions =suggestions.UpdateSuggestions(date)
// create view model
MyModel model= new MyModel(suggestions);
return View(model);
}
As I review more code and blog posts from lots of MVC sources, I still haven't wrapped my mind around what is "posted" when a request is made. I realize MVC doesn't support post, but I'm having trouble finding resources that can explain it well enough to understand.
Inside the controller's public ActionResult nameOfAction(what the heck goes here?) { ... } what are my parameters?
Sometimes it looks like Visual Studio scaffolds (int id, MyObject myobject) for an Edit-style action--it includes something from my model, but not always.
Sometimes, it's (int id, FormCollection collection) for a delete-style action. Why not use the modeled object here? Is a FormCollection object always "posted"?
Sometimes, I see (RouteInfo routeInfo) which isn't recognized in my MVC2 Intellisense (is this MVC1 only or something?)
How can/do/should I establish these parameters? I think this will help me a lot at design time.
What gets post back from a form in MVC is the form data which includes each form element in a keyvalue pair.
If you only need this information then you would use:
public ActionResult nameOfAction(string name, string lastName, string etc)
MVC has some smart data model binding which takes the form data and automatically creates an object which is part of you domain model. For instance it could automatically create a Person object with the provided form data.
I believe there is a security concern with this as a user of your site may post data which is not part of your form and guess what your models are to inject their own data.
I dont think this is a massive issue though and this is the way I would go.
I think you can use the anti-forgery helper to prevent users from posting back data which is not allowed in a form. anti-forgery
Use strongly typed views with a view-model and the strongly typed helpers. Then when you POST, you should get an instance of that view-model out.
I'm wondering how you keep a constant value of the Model in an ASP.NET MVC framework. Like when adding something to the Model through the view. You go back to an action in the controller but where do you keep the Model? Is it a private in the controller? or is it passed back and forth from the view to the controller because if it gets big then you are passing alot of data back and forth to add/delete a single item from the Model.
Also any small examples to show this?
Thanks
What are you referring to? Are you meaning a database table loaded up into an object such as Ruby on Rails's ORM -- typically the 'Model' is a series of interfaces or domain objects that load data into objects from the database .. or more simply just the database period.
Please be more specific. There are many MVC frameworks and many different kinds of 'Models'
I think you should check out a ASP.NET MVC tuturial like NerdDinner (from "Professional ASP.NET MVC 1.0"). Scott Guthrie has posted a html version of the tutorial on his site. It's a fairly simple site that they build in the tutorial, and is a great intro to ASP.NET MVC (in my opinion).
There are also some good tutorials on the ASP.NET site.
Hope these help you with .NET MVC, it's a great framework to use!
You can pass the model to the page and you can then use UpdateModel(model name) within your controller.
Each member in the model must be a property with a getter and a setter.
On the page you can hold the data in say a hidden field if you need to maintain the value outside of state.
If you have problems using UpdateModel then you can use the following in your controller;
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyAction(int? id, FormCollection collection)
{
string commentText = collection["myFieldName"];
}
This will normally get your values from the model.
Hope this is what you were asking.
Think of the model as a data transfer object. In a list, display only or edit page, you pull it out of a data layer as a single object or a list of objects. The controller passes it along to the view and it gets displayed.
In the case of an insert, a new data transfer object is instantiated upon post back and is updated with the posted values. Then sent back to the the data layer for persistence.
In the case of an edit, it comes from the data layer on the HTTP GET request and is used to pre-populate the HTML form. Then on post back, the data transfer object gets updated with the posted values and sent back to the the data layer for persistence.
Definitely checkout NerdDinner or Stephen Walther's samples.
I've been playing around with the ASP.NET MVC Framework and the one thing that's really confusing me is how I'm meant to do server side validation of posted form data. I presume I don't post back to the same URL, but if I don't, how do I redisplay the form with the entered data and error messages? Also, where should the validation logic go? In the model or the controller? This seems to be one of the few areas where web forms are much stronger (I miss the validation controls).
Here's an overview of the flow in MVC:
/new - render your "New" view containing a form for the user to fill out
User fills out form and it is posted to /create
The post is routed to the Create action on your controller
In your action method, update the model with the data that was posted.
Your Model should validate itself.
Your Controller should read if the model is valid.
If the Model is valid, save it to your db. Redirect to /show to render the show View for your object.
If the Model is invalid, save the form values and error messages in the TempData, and redirect to the New action again. Fill your form fields with the data from TempData and show the error message(s).
The validation frameworks will help you along in this process. Also, I think the ASP.NET MVC team is planning a validation framework for the next preview.
You might want to take a look at ScottGu's latest post for ASP.Net prev 5. It walks through a validation sample that is very interesting:
http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx
As far as I can tell everyone is still trying to figure out the "standard" way of doing it. That said definitely check out Phil Haack and Scott Guthrie's latest posts on MVC and you'll find some interesting info on how they did. When I was just playing around with it for myself I created a ModelBinder for the LinqToSql data class that I had generated. You can check out this post to find out how to put together a basic ModelBinder:
ASP.Net MVC Model Binder
The in your action if you had created a "Product" ModelBinder you would just declare the action like so:
public ActionResult New(Product prod)
And the model binder will take care of assigning posted data to the objects properties as long as you've built it right anyway.
After that within your GetValue() method you can implement whatever validation you want, whether using exception's, regex's, or whatever you can make a call like:
(ModelStateDictionary_name).AddModelError("form_element_id", "entered_value", "error_message");
Then you can just throw a <%= Html.ValidationSummary() %> in your view to display all your errors.
For client-side validation I just used jQuery. After you get a basic sample set up though you can start doing some interesting things combining all that with Partial Views and Ajax calls.
Have you taken a look at this?
http://www.codeplex.com/MvcValidatorToolkit
Quoted from the page
The Validator Toolkit provides a set
of validators for the new ASP.NET MVC
framework to validate HTML forms on
the client and server-side using
validation sets.
I'm afraid that someone more MVC-savvy than me would have to speak to where in the architecture you should put things.
I'm just learning the MVC framework too so I'm not sure how off this is, but from what I understand you would have a form on a View such as Edit.aspx. This form would then post to the controller to another action method such as Update() passing in the contents of the form that you set in Edit.aspx as parameters.
Update(int id, string name, string foo)
You could do the validation within that method. If all is ok,
return View("Item", yourObject)
There is Castle.Components.Validator module in Castle project. It's very agile and powerfull. It generates validation rules based on model attributes (or any other source) and even able to generate JS validation using jQuery, Prototype Validation, fValidate and other.
Of course it's wise to abstract validator away behind IValidationEngine interface.