Few basic query about ASP.Net MVC - asp.net-mvc-3

i am new in mvc and learning it by going through wrox book. i encounter few thing and i am looking for good clarification.apologized for asking many question in one shot.
1) #Html.DisplayFor & #Html.EditFor
when we use #Html.DisplayFor then what html control render at client side ?
when we use #Html.EditFor then what html control render at client side ?
2) what ModelState.IsValid does ?
i always see ModelState.IsValid return true ? when it actually return false ?
3) how to extract the form submitted value from ModelState ?
i try to do it this way like ModelState["Name"] or ModelState["Name"].ToString() both gives error.
4) what is Remote Validation in mvc ?
5) when we use html helper to render text boxes then how could i attach multiple attribute with it. i tried this way
i tried to display model text like this way but did not
#Html.LabelFor(m => m.Name, new { #id = "name", #class = "", title = "#m.Name" })
can't we specify or assign model text like this way title = "#m.Name" ? if not then how could i assign a model text to title attribute ?
when we need to use # sign when we work with html controls attribute
6) Is it possible to call different type of function/method directly from view
i like to know that
a) if i have few static function or static classes function then can we call it directly from view ?
b) can we can controller method directly from view ?
c) how to call any generic method directly from view?
d) is it possible to call any action method directly from view ?
e) can we can call any model method directly from view ?
which is possible and which is not please explain with reason and sample code
7) regarding data annotation
i want to work with data annotation but i want data annotation should render different js in page for fancy validation message. how to use different jquery validation plugin with data annotation....where we need to change in code.
please answer all my question point wise with example & sample code for better understanding. thanks

when we use #Html.DisplayFor then what html control render at client side ?
That's totally gonna depend on the specific type of the property you are calling the DisplayFor on. The DisplayFor helper will analyze the specific type of the property used in the expression and invoke the corresponding display template. You could also write custom display templates for your view model types. Brad Wilson wrote a nice blog post about templates that I invite you to go through to better familiarize with the basic concepts: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html
There are a series of posts, make sure you've read them all.
when we use #Html.EditFor then what html control render at client side ?
That's totally gonna depend on the specific type of the property you are calling the EditorFor on. The EditorFor helper will analyze the specific type of the property used in the expression and invoke the corresponding editor template. You could also write custom editor templates for your view model types. Brad Wilson wrote a nice blog post about templates that I invite you to go through to better familiarize with the basic concepts: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html
There are a series of posts, make sure you've read them all.
i always see ModelState.IsValid return true ? when it actually return false ?
When there are errors added to the ModelState. Could happen if you have used some data annotations on your view model to do validation and the values submitted to the server failed this validation. Normally it's the default model binder that is adding error messages to the ModelState (making ModelState.IsValid return false) when binding the request values to your view model.
i try to do it this way like ModelState["Name"] or ModelState["Name"].ToString() both gives error.
In ASP.NET MVC you use a view model. Your [HttpPost] controller action takes a view model as parameter which is a class specifically designed to meet the purpose of your view logic. Here's an example of how a typical POST action might look like in ASP.NET MVC:
[HttpPost]
public ActionResult SomeAction(MyViewModel model)
{
if (!ModelState.IsValid)
{
// validation on the view model failed => redisplay the view
// so that the user can fix the errors
return View(model);
}
// At this stage you know that the model has passed validation
// It is here that you would typically map the view model to some domain model(s)
// and pass them to your DAL for some processing.
// Finally when this processing completes redirect (Redirect-After-Get pattern)
return RedirectToAction("Success");
}
4) what is Remote Validation in mvc ?
It's a view model property decorated with the [Remote] attribute which in turn emitted some HTML5 data-* attributes on the corresponding input field. In turn the jquery.validate.unobtrusive.js script will use those properties to send an AJAX request to the corresponding controller action to perform validation before the form is actually submitted. Please feel free to read the corresponding documentation: http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx
a) if i have few static function or static classes function then can
we call it directly from view ?
No of course not. This question doesn't have any sense. The view doesn't know about any server side specific things other than controller actions. So if you want to call something from a view this something in the ASP.NET MVC world is called a controller action. You could of course us AJAX or something to call it.
b) can we can controller method directly from view ?
Yes, of course, if this controller method returns an ActionResult in which case this controller method has a name: A controller action.
c) how to call any generic method directly from view
Absolutely impossible. That would have been a huge security vulnerability if it was possible. You can only invoke controller actions from a view.
e) can we can call any model method directly from view ?
No, for the Christ sake. I repeat: That would have been a huge seurity vulnerability if it was possible. You can only invoke controller actions from a view.
i want to work with data annotation but i want data annotation should
render different js in page for fancy validation message. how to use
different jquery validation plugin with data annotation....where we
need to change in code.
Sorry, I have strictly no idea what you are asking here. ASP.NET MVC client side validation is tightly coupled with the jquery.validate plugin (whose documentation I invite you to read to better understand its functionality: http://jqueryvalidation.org/documentation/). And if this plugin doesn't meet your requirements, after all, ASP.NET MVC view spits HTML, so feel more than free to use some of the gazillions available javascript validation plugins out there that might fit your specific needs.
Hopefully this answers some of your questions. Next time you post a question on StackOverflow make sure that it is very specific and not asking about the philosophy on the entire world (as you did here). Make your homework, read the documentation, and if you have specific issues, post your code, explain the difficulties you encountered with it, and we will be glad to help.

Related

Model View Controller (MVC) info

If i use the MVC pattern to create my Spring project, is it wrong to call the Controller from the View?
Is this schema right?:
View calls the Controller
Controller performs operations and put data result into the Model
View reads data from the Model
Edit:
In my index jsp there is a menu with several categories of articles. I want to pass the name of the category to the controller. The controller calls the method of a beans which executes a query and returns the list of articles presents into the database.The Controller puts this list into the model and the View read this list from the Model.
Thanks
What you say (in your comments) is not specially wrong, but it does not make sense.
Either the categories are known when you build the view, and then it is the controller role to collate all information and put it into the model before calling the view with the model.
Or the category is chosen through a user interaction. But at this moment, the JSP is over for a long time : the response has been committed and transmitted to the browser. The only possibility is to prepare a new request (with a form or with ajax), send this new request to the server, where it will be handled by a controller, which will collate data into a (new) model and pass it all to a view
Depends what you mean by calling. But yes, View doesn't know anything about the controllers. It sends HttpRequests, and than the mechanism doing what you describe kicks in. There's the famous schema from spring docs, basically your bullets described via diagram. The point with respect to your question is that the view doesn't call the controller rather sends the request
I think you will find your answers in article mentioned below :
http://docs.spring.io/spring-framework/docs/2.5.3/reference/mvc.html

RESTful design pattern in MVC?

I'm designing an application trying to follow the REST spec. I'm trying to figure out the best way to design it.
So let's say I'm doing a POST call that so I have a "post" method in my controller and model
// in controller
function post()
{
//call post model here
}
In my post request I need to make the following checks:
-validate fields
-make sure item name is unique for that user
-make sure there are less than 10 items
-etc (there could be more cases)
Now in controller post function I will return a REST message and status code based on whatever happens, which is fine, but I'm curious to know where it's better to keep all those checks.
I can put all the checks in the model and then return some kind of array like:
array('text' => 'return response text/array or whatever here', 'code' => '200/400/etc')
Then just return this in the controller, or is it better to break up those checks into individual functions within the model and then do all the checks in the controller?
// in controller
function post()
{
//if validation fails -> send response
//if name is not unique -> send response
//etc...
}
From a design point of view, if I ever wanted to potentially call the "post" method in the project model from other methods, it would not have an all encompassing function to handle it, however if I do keep it all in one model function it doesn't give me a lot of reusability. If I had to pick sides, chances are I probably wouldn't need to reuse those "check functions" too much anyway, however it also seems weird to have all that response info in the model rather than the controller.
Can anyone please give me some input on this.
I would not create post method inside the model (although having it in the controller is perfectly fine) simply because you just put code/model in such a frame that is not re-usable plus less readable. For instance, instead of post method in the model I would create create method.
There is no one-fits-all way for data validation. I like creating validation classes which have only one method validate for various data types (e.g. username validation class checks if it matches regex and is unique). It's better than copy pasting the validation code to every action (DRY). Where to call this class method? It depends. You can simply call that it in the action. Since the validation code is inside the validation class, it will look alright. You can also create a mapper which takes the request, determines what validations have to be performed and etc. but it might be overkill and is hard to do properly (maintainability wise).
For output again - DRY. It depends on what MVC framework are you using and there might be a good solution for this already. If not, you can create a class for that (yup, I am DRY maniac). You pass response code, array (or string) with response and class nicely wraps everything into JSON, XML format. Advantages: if you change then output format then you need to change only in one place.
Also consider using Remote Facade pattern.
Hopefully, you found something useful in this post.
I would separate the API from the MVC application and use Apify

Add ASP.NET MVC Routed URLs to view-model objects (for use in JSON)

I'm writing an application which uses ASP.NET MVC with JSON.NET as the server, sending JSON to the client which is read by Knockout and then displayed with data-bindings. This is all working wonderfully, except for one problem:
I have a class Customer which is used to generate a ReviewAuthorViewModel class - the latter is meant specifically for JSON serialization and removes unnecessary fields, circular references, etc. On the client, I want to render a link to the Customer's profile page, with the URL coming from a defined MVC route "user/{username}". Because I'm sending this via JSON, I don't have a .cshtml page in which I can call Url.Action.
The question is: For an arbitrary object, how do I most efficiently/elegantly get a URL for an action with some data, without a .cshtml view?
I'd prefer a solution that doesn't require extra code in each action, but that may be the only choice apart from recreating the routing tables client-side in JavaScript. Below are the things I've already tried, and what was unsatisfactory with each.
Solution Attempt 1
Call the UrlHelper.Action method in the ReviewAuthorViewModel class. However, the UrlHelper requires a request context. For the sake of separation of concerns, I don't want my view model to have a dependency on System.Web.Routing, nor do I want it to need a request context to function.
Solution Attempt 2
Create a class RouteInformation with members Controller, Action, and Data, and an interface IUrlViewModel with two properties, a get of type RouteInformation and a get/set string named Url. The view models needing links then implement this interface, and controllers look for view models of type IUrlViewModel and run UrlHelper.Action with the information from the view model's RouteInformation instance, storing the result in the Url property.
This one works but without reflection I don't know how to find view models implementing IUrlViewModel within other view models, and it feels very kludgy.
Solution Attempt 1 is the OK solution. In asp.net-mvc, view models are part of presentation layer, designed specifically for use with views. You should not worry about having view model depend on asp.net specific things. In fact, they should be coupled, as they should be designed to maximize simplicity of view generation and data exchange between web server and web client. And it's good solution to create separate view model and not use Customer class directly for clients. It wouldn't have been OK if Customer was dependent on Routing.
In fact, you could set that property in controller -
[HttpGet]
public ActionResult Get()
{
var viewModel = new ReviewAuthorViewModel();
viewModel.ProfilePageUrl = Url.Action("Index", "Profile");
// return viewModel;
}

Razor and Creating Helpers for Users: Html.*

I have an ASP.NET MVC3 (with Razor) application where I allow users to specify components for the view -- like the layout, or partials that I use to render content. (For example, I have a model that has a Title and Description, and I allow users to specify a CSHTML partial in a particular directory that I use to render the data.)
The problem that I'm running into is isolation and ease of use for my users. For example, they can currently write code in their partials like:
#Html.ActionLink("edit", "Edit", "Content", new { Id = Model.Id }, null)
I would instead like them to write something like:
#SomeHelper.EditLinkFor(Model.Id)
Right now, my controllers are all part of the public API. Users need to know controller and action names to specify certain links (eg. edit link). I would like to provide a simplified API.
But how do I do it? If I just create the SomeHelper class, trying to call #Html.ActionLink isn't making much progress. I tried writing:
return System.Web.Mvc.Html.LinkExtensions.ActionLink(null, content.Title, "Details", "Content", new { Id = content.Id }, null);
But I get a null pointer exception. Creating an HtmlHelper instance for the first parameter is not easy.
What are my options? Am I stuck with providing them full access to all my controllers as part of my API? Is there no way to provide a simplified API for their consumption? (I'm not trying to block them from writing Razor code; only encapsulate and simplify calls, and eliminate an underlying dependency on my controllers and models.)
There are a few possible options:
a) You can extend the HtmlHelper with your own class
b) Reusing #helpers accross multiple views
c) Change the base type of your views
The html helpers provided are pretty basic - but you certainly can create a helper. Just be careful - the existing API is provided and fits in exactly with the rest of the MVC programming model (Ajax and html helpers and the route syntax)
The problem is in how you call the code. Please post all of your code so we can check it out.
The question is exactly what do you want to do? You want to create a helper for
EditLinkFor - but something is failing, can we see all the code?

MVC: pass model / model data to a view from a controller?

If a view needs to acces data from a model, do you think the controller should:
a) pass the model to the view
b) pass the data of the model to the view
c) neither; it shouldn't be the controllers concern. Let the view access the model directly to retrieve the data. Only let the controller give some parameters the view needs to filter the data from the model.
d) it depends on the situation.
e) none of the above, but [...]
Thanks
After some debate in the comments to an answer that was deleted by the user, maybe this needs clarification. My view of the MVC architecture is biased towards that of the Zend Framework (php) in which an action in a controller by default has a default view assigned to it. So it's not so much the model that dictates which view is approporiate, but rather the controller. Do you feel the model should dictate what view is appropriate? The only way I see fit to let the view be build based on a model, is by letting the controller pass the model to the view. Are there other techniques to let a view access a model without the controller being involved? Or is it perfectly fine to let a controller pass the model to a view, so that the view can be build based on the models attributes?
e) None of the above; pass in a view-optimised "ViewModel".
Example in ASP.NET MVC:-
public ActionResult Details(int id)
{
Product p = ProductService.GetProductById(id);
if(p == null) { return RedirectToAction("Index"); }
ProductViewModel model = new ProductViewModel(p);
return View(model);
}
both a) and b) "will do" subject to d). Never ever c).
Typically, the ViewModel just encapsulates the Model (if nothing complicated is going on, your view could access the model directly via ProductViewModel.Product). If the view needs to do anything complicated with the Model however, it's the ViewModel's responsibility to do that, rather than the responsibility of the Controller, or the View.
This keeps your concerns nice and segregated. Your Controller doesn't care exactly what specific data your View needs (beyond the fact that it's rendering some Details of a Product), or especially what format your View needs that data in. Your View doesn't depend on the implementation details of your Model. Your Model doesn't have to concern itself with how it's being Viewed. If you have two Views rendering Products (e.g. Create, Edit, Summary, MoreDetails etc), those Views can have different ViewModels to expose only the data that each specific View needs, so your Views aren't depending on eachother. Lovely :)
Some further reading from various viewpoints:-
http://www.thoughtclusters.com/2007/12/datamodel-and-viewmodel/
http://stephenwalther.com/blog/archive/2009/04/13/asp.net-mvc-tip-50-ndash-create-view-models.aspx
http://www.nikhilk.net/Silverlight-ViewModel-MVC.aspx
I think ViewModels are a particularly .NET thing, but I see no reason at all why the pattern can't be used in PHP.
Hope this helps.
Ideally, it should "pass the data of the model to the view" so the view doesn't need to know any explicit structure of the model and thus be more reusable and designer-friendly.
But practically, "pass the model to the view" works as just fine. Most of the time you will need a new view anyway because clients never share favorite colors (if you know what I mean :-) so views re-usability doesn't justify having a lot of tedious code required to copy data from the model to the view.
What you should concern more about is the modularity of the controller itself, since many websites do share common functionalities (controllers) such as web forums or a news listing but not looks (views)
This is late I know, but I'm having this issue on a project I am working on. I started with a) - for simplicity - and now running into road blocks.
I am coming around to this method:
e) None of the above; pass in a view-optimised "ViewModel".
because it avoid bloating both your model classes (instances of which are "transaction objects") and your views. For example, you may need to render a number with a specific number of decimal places (this is the problem I am having now).
With an intermediate "ViewModel" this is easy - you just write the relevant ViewModel "getXXX" method to return the number formatted how you wish.
If you just pass the model directly into the view, you will need to specify it in the view every time you use this figure (going against DRY - don't repeat yourself), or alternately, add a rendering method to your model classes (which goes against a class being for one purpose only).
Cheers
a) pass the model to the view
Otherwise the controller is manipulating the view via screening the model. This is what would happen in "b) pass the data of the model to the view". The b) option doesn't really even make sense in the pure MVC pattern. After all, the model IS the data. If the model is changed for consumption, a view has been applied, whether you choose to do it in the controller and pass it off as a controller function. What happens when you have a different view? Does the controller screen its data differently? You soon have two views for model, the controller sub-view and the view itself.
For me that's e).
As already mentioned here, ideally the view and the model are decoupled. The way I prefer to implement this is to have a viewHelper for a model. This has the API the view can use to get the data. Now views are not affected by changes in the model and the view doesn't need to 'get' the internals of the model. These are hidden away by the viewHelper.
example:
class Post {
public function export(ViewHelper $helper) {} // I try to avoid getters when I can
}
class PostViewHelper {
public function getTitle($parameters) {} // title of current post in the loop
}
class PostView {
private $helpers = array();
public function loadTemplate($path) {}
public function addHelper(ViewHelper $helper, $name) {}
public function __get($key) {} // if exists $this->helper[$key] etc
}
in a template
<h1><?php $this->post->getTitle(); ?></h1>
You may want to implement this differently. But my point is in how the view and the model are decoupled, introducing an intermediate viewHelper wich creates the view/template API.
I don't think it's that complicated. a or b.
The controller's job is to manage the relationship. It finds the model and view and provides the view all the model data it needs to do its job. That's it. MVC doesn't dictate the exact form the data takes.
(a) Start simple. It's pretty natural to pass the model objects directly to the view. If you have a page about a Foo, just pass the Foo.
(b) But at times-- and only at times-- you create a value object / DTO to get the data to the view (called a ViewModel above). Do this when there's a mismatch between the view and the native model, such as summary views. If the view is presenting a summary of 1,000,000 objects, you don't want to hand the view the model objects; you want to hand the view a summary of the 1,000,000 objects.
And the exact implementation really depends on the language and framework you are using. But I think these guidelines are a good start.
uhh b.
i dont really see the difference between a and b other then some technicallity of how you will be passing data.
usually you pass a map of data to the view with some data from the model

Resources