How to use same scripts in views - asp.net-mvc

I have a view for creating an entity by filling a form. That form contains several inputs and 2 datatables table. i write a considerable amount of JavaScript code for initialization and validation of the inputs. For editing the entity, i need the 95% of inputs and JavaScript codes.
First, I tried to move the common codes to a partial view but some of them worked and some of it didn't work. For example the tables not initialized.
As a second approach, I can also write a lot of if-else to check the current page (between Create and Edit) and do proper action.
How can i have two views and common codes in both? Is there a better or functional approach?

save your javascript code as js file. Drag and drop its link where you want to use it :)

You can use the same view for Create and edit functionality.
And regarding the inputs, you can take one property in the model which will indicate whether to show or not to show that input on UI.
Model:
For eg. Public string displayInput=[none/block]
view:
You need to set the value of displayInput field properly when you want to show all fields and when you want to hide some fields.

Related

Rails, One controller and one model but many templates, need advice

I have one model with a lot of attributes and one controller, but I also have nearly 100 templates. Approximately 90% of fields and view in this templates are the same. User can fill any template, save it and ,as needed, print it as PDF. What is the best approach of implementing this kind of relation?
I see only one way:
1. 1 model, 100 controllers(because all templates have to have all REST actions) and included module with same actions for all, and 100 shared partials for form and view.
Ideally, of course, 1 model, 1 controller per template, but it is not the DRY'st way.
Am I wrong? And there is another simple way with one model, one controller and 100 partials?
Will be appreciate for any advice.
This is a solution that could be implemented provided your scenario is simple. (I am giving this because you have not mentioned anything about the so called templates and types of fields).
Anyway, have one controller and one model (Because you say 90% fields are same. Having 10% nulls aint a big deal). Then create a form with all these fields organized as templates. Have a select box to select the template and based on that hide or show your fields with JavaScript.
Assuming you have a field to indicate template_type in your model you wont be having any problem saving this and displaying. Or even switching templates by editing your model.

MVC Razor How to get the model in the Controller on HttpPost when the model is dynamic

I'm working a feature in the application where model will be dynamic in the sense that any settings data could be displayed and the view will get the model based on what tab they clicked on. I use Hidden field to store what the settings name was because they are same as model name. for ex., if tab1-> Settings1 then Model is Settings1[already exists in the Model].So I used # model dynamic in View and used #Html.EditotForModel() to draw the required UI based off the model. My problem is when I do HttpPost on Edit currently I'm using FormCollection to read the data on that page when I declare the model name in the param it will get it for me but I don't know which model is coming back other than by the Hidden variable and I need it because the Model validation is broken because of this issue. Any help or feedback is appreciated? I can give more details if required? Has anybody crossed this issue before??
Dynamics can be a good thing and a bad thing. Using them on models that have a common interface in a controlled manor is best.
There are different options that you can look at:
1)
Have you tried making the action method accept a dynamic type? That might be the easiest way.
You might have to set up a casting helper to cast the object to the correct type based on the hidden field.
2)
I have a similar idea in some code, but I created a viewmetamodel class that contained all my types as nullable properties. My action method accepts this viewmetamodel type and validates the properties that are not null.
In line with this, if your data is not too large, then you could load all the settings tabs and use Jquery apply the tab with on click.
3)
You could also create #sections or use EditorFor(c=>c.settings) for each tab. That way each tab will load a type safe object. You would need to create controllers for each.
I would say pick the easiest method for you. I hope that this at least gives you some ideas.

Should I render optional sections of a form via partials?

As an exercise in learning .NET, I'm moving some simple forms over into MVC, and have run into an issue. The form in question is a multi-part form that has option sections. For example, Section 0 is static and contains information like username, real name, email address. After that is a radio button with several options. If you click the first radio, it displays Section 1. If you choose the second, it displays Section 2, and so on.
In WebForms this was no biggy, as I just validated on postback and said if Radio1.Selected validate this, if Radio2.Selected validate that, etc. So now I've got a strongly-typed view with [Required] members, which obviously isn't going to work - I can't require members that aren't always going to be required.
With that said, is this the correct approach to the problem:
Create the members that belong in Section 0 in my strongly-typed view model class.
Create references to each partial's strongly-typed class in my view model class.
Create the partial views and then render them in the main view.
Depending on which radio button is selected, render the appropriate partial view.
Validate the model like usual...which hopefully will cascade to the partial models.
Does this make sense, or is the approach wrong?
That's a typical scenario where you need conditional validation, i.e. if some value is set then validate that some other value is required. Achieving this with static data annotations which are simple attributes baked at compile time can quickly turn into a nightmare due to their declarative nature. Well, you could always roll your own custom validation attributes but the problem with attributes is that you will have to specify property names as strings as they need to be known at compile time.
That's one of the reasons why I use FluentValidation.NET. Not only that validation rules are separate from the view models and that it integrates really nicely with ASP.NET MVC but handling scenarios like this would be very easy. You could have a sub-view model containing all the properties of the sub-section and then conditionally include it based on the value of a given property on the main view model inside its validator.

Should the model be responsible for holding lists that will ultimately populate dropdownlists in the view?

This might be similar to ASP.NET MVC - Populate Commonly Used Dropdownlists.
I want to populate DropDownLists. Some of it is static data. Some of it comes from the Database. A couple of times I found myself forgetting to call the code that populates my lists and sets the ViewBag accordingly. It is almost worth adding a unit test for this. The only way I think that this suits a unit test is if you place it in model/service. Is there a best practice for this kind of thing?
I'd suggest that the data is contained within the model but is perhaps constructed by a html.helper method. this way, you keep the plumbing markup out of the view and leave the controller free to invoke the neccesary view and model.
You could also of course hand it off to a partialview with an <IList<SelectList>> model.
cats and their skin :)
If you follow the spirit of the pattern then the Model should supply the View with everything it needs to present to the user that's not static. If you have static dropdown lists then you could say that these could be constructed within the mark-up. If you are passing a SelectList to the View from your Action then I'd stick it in the Model to make things simpler and more coherent.
My rule of thumb is that the data must somehow be in the model, either as a ready to use SelectList or at worst in some container that can easily be turned into a SelectList using a LINQ-to-object call.
The bottom line is that the view should never contain any non trivial code.
EDIT (answer to your comment):
I try not to put too much code in models. Models are more like a simple bunch of data gathered by the controller and used by the view.
Regarding simple and/or common things such as the days of week, I believe an HTML helper is the most elegant solution. See WayneC's answer in this question.

Make all form fields readonly in MVC

I am displaying 3 or more versions of a form. One version is an edit form to edit all fields. A second version will be a read only version of the same form which will be used to show all the same fields but with all fields having readonly="true" on the client side so that the user cannot enter data. The readonly fields need to use a different css style. This is to display archived data. I am already hiding the submit button so they can't submit but I want the form to look like it is readonly. A third version will have some fields readonly and some editable for a particular class of users that has limited editing privileges.
I am using ASP.NET MVC 1.0. How do I modify all (or a subset) of the fields displayed so they are readonly. I would like to iterate through the collection of fields in the controller and set them all to readonly and also set the correct css class. I don't want to have to put an if statement on every field in the .aspx file (there are 40-50 fields) and I'd prefer not to have this on client side so I can prevent users from modifying javascript/html to edit things they are not supposed to.
TIA,
Steve Shier
Keep in mind that even if you set the tags as readonly on the server side, users can still change them through a variety of means, and whatever the value on the form is before it gets sent back to you.
Certainly the easiest way is client-side with jQuery:
$(function() {
$('input, select, textarea').attr('disabled', 'disabled');
});
Or, you could do it in your View, but it's ugly. Off the top of my head, you would need some sort of bool passed into the View (via ViewData I suppose), and check that on each Input to see if you should add the disabled attribute. Not my idea of fun...
I would have different views that correspond to your states and then choose the view depending on which state you are in. You could also implement it with partials, breaking down the pieces so that you can easily include editable or read-only versions of the different sets of elements. The read-only view, then, need not even include a form element. You could also present the data in spans, divs, or paragraphs rather than as input elements.
Note: you'll still have to check whether the current user has the ability to update/create data in the actions that process form submits. Just because you limit the ability to view data in a read-only format, that won't stop someone from crafting a form post to mimic your application if they want. You can't rely on hiding/disabling things on the client to prevent a malicious user from trying to enter/modify data.
I usually use partial views to represent forms and/or parts of forms.
I can think of two simple ways to do what you need (as I understood it):
<% Html.RenderPartial(the_right_partial, model); %> where the_right_partial is either a value passed from the controller or a helper (in which case, the_right_partial(something));
pass a bool or enum paramether from controller representing editability and then using a helper to obtain the right htmlAttributes, like:
<%= Html.TextBox("name", value, Html.TheRightHtmlAttributesFor(isReadableOrNot)) %>;
There may be other ways, like creating new helpers for input fields which accept an additional isReadableOrNot arg (but it seems an overkill to me), or like mangling the html/aspx in some odd (and totally unreadable/unmaintainable way), but I'd not suggest them.
Notice that using html attributes like disabled is client side, and with tools like firebug it takes just two seconds to change them.
Others have already said it, but I also have to: always assume that the user will do his/her best effort to do the worst possible thing, so check the user rights to modify stuff on server side, and consider client side checks as a courtesy to the user (to let her/him understand that the form is not supposed to be edited, in this case).
Since I am trying to use a single partial for the different states of the form, I am thinking I will create helper functions which will display correctly based on the state and the user. The helpers will use a dictionary of fields that will indicate under which condition the field is read only. I will still have server side checks to make sure data is valid and the user is authorized to make changes.
Thanks for all of your ideas and help.
Steve

Resources