Naming of ASP.NET controls inside User Controls with ASP.NET MVC - asp.net-mvc

I am wondering if there is a way to make ASP.NET controls play nicely with my ASP.NET MVC app. Here is what I am doing.
I have an order page which displays info about a single Order object. The page will normally have a bunch of rows of data, each row representing an OrderItem object. Each row is an ASP.NET User Control. On the user control there is a form element with two text boxes (Quantity and Price), and an update button.
When I click the update button, I expect the form to post the data for that individual OrderItem row to a controller method and update the OrderItem record in the database.
Here is my problem: When the post happens, the framework complains because the fields on the form don't match the parameters on the controller method. Each form field is something like "OrderItem_1$Quantity" or "OrderItem_2$Price" instead of just "Quantity" or "Price" which would match my method parameters.
I have been told that I can overcome this by making sure that the IDs of all my controls are unique for the page, but allow the NAMEs to be repeated between different forms, so that if a form for an individual row is posted, the name can be something that will match what is on my controller method.
The only problem is that I am using ASP.NET controls for my text boxes (which I REALLY want to continue doing) and I can't find any way to override the name field. There is no Name propery on an ASP.NET control, and even when I try to set it using the Attributes accessor property by saying "control.Attributes["Name"] = "Price";" it just adds another name= attribute to the HTML tag which doesn't work.
Does any one know how I can make this work? I really don't like all of the HtmlHelper functions like TextBox and DropDown because I hate having my .aspx be so PHP or ASP like with the <%%> tags and everything. Thanks!

I think you're straddled between two worlds of ASP.NET WebForms and ASP.NET MVC. You really need to use the Html.TextBox methods, etc. in MVC. This gives you complete control over the markup, which is one of the main benefits of MVC.
The very problem you're having with control over the generated HTML, e.g. getting two name attributes, is exactly what MVC is designed to address. If you stop fighting it and go with the flow, it'll work much better.
<% %> tags aren't a problem unless you have logic in there. Putting simple presentation logic on your view is fine.
If you don't like this, then maybe it's better to stick with standard ASP.NET.

Related

ASP.NET MVC List of Web Components in Model

I need to get dynamically a list of Web Controls from View to be used in the model(dropdownlists, inputs, checkboxes, ...). Is it possible? I generate the controls in Razor.
My application should store last values of all controls for each user into the database and use them as predefined values for the next call of the form.
Any advice would be appreciated.
I need to get dynamically a list of Web Controls from View to be used in the model
First of all, you're probably going to find MVC a lot easier to understand if you abandon terms like "web controls" and the like. Your view, which may not may not be utilizing helpers to do so, is simply building HTML. Nothing more.
But more to the point, what you're proposing is exactly the opposite of what MVC does. Your model should have no knowledge of the structure of the view. (inputs, selects, other form elements, etc.) The model contains the data and business logic necessary to render the view. The view then uses that data and logic to build its interface.
You can post the values from the resulting HTML form to a server-side action. Then from that action you can store those values in a database or do whatever you like with them. If the key/value pairs of those values can logically be structured into the form of a model then the action can accept that model as a parameter, if not then it can also just as easily accept parameters for each individual value. (Though if you find yourself using a lot of parameters it would be better to build a simple view model just to encapsulate them.)
The order of operations is something like:
A request is made to a controller action.
That controller action invokes logic on a model and provides that model to a view.
The view binds its UI elements to the model's data and renders the interface.
The user interacts with the interface and uses it to perform a request to another controller action.
That controller action receives the data from that request, performs server-side logic, etc.
and so on...

asp.net mvc implicit population of input fields

In our asp.net mvc I've created view with two partial views inside.
That view accepts model of some type, for example Customer.
First partial view doesn't have model because it is search form with empty field.
Second form is form with populated fields.
What I found out that on first view, if I have called input fields like properties in model and if I don't provide value for them, mvc implicitly binds values from model to the fields.
First I was thinking is some of kind of mistake, but then I've expiremented little bit with a code:
-I've added native input element with id and name called the same like model, input field is empty in browser
-If I try the same thing with Html.TextBox helper and don't provide value, mvc gets that value from my model object(by name of property/field) and in browser that field is populated.
Is this a bug or am I doing something wrong?
Thanx
That's by design.
I'd recomend reading:
http://asp.net/mvc
http://weblogs.asp.net/scottgu/archive/tags/MVC/default.aspx
and last but not least:
http://channel9.msdn.com/Events/MIX
especially mix10 has a tonn of sessions about mvc
all are good read and watch (-:
That is by design. If you send a model to a view and you're using the HTML input Helpers that come with ASP.NET MVC, they'll implicitly populate themselves from the model.
This is helpful in many situations. If you don't want this behavior, you can always NOT use the helpers or write your own simple helpers.

How To: Use MVC and Ajax to add / remove a row in grid for data entry + model binding?

I'm new to Ajax, but I think I know how to reasonably use MVC + model binding.
What I'm trying to do is to create an Add button (or Ajax.ActionLink) to add a new row in my grid for data entry. Example: Think of a typical Order entry system with Order (header) and Product (items). My OrderViewModel contains an "Order" object, and the Order object contains a collection List.
The way I plan to do this is that my View render the grid in a PartialView, and the PartialView is a simple for-loop to create the table tags from the List. I will use the default model binder (for collections).
Anyone have suggestions on how to do this?
I've already figured out how to do this using jQuery, but I want (i think I want) to try and use Ajax so that I can add my custom business logic (e.g. like setting defaults, translations, etc.)as opposed to do this client-side.
In other words, I want to do do something similar to what the Telerik grid does with its Ajax Editing with the Add/Remove link/buttons.
Tips and sample code would be greatly appreciated.
One of my challenges, and not sure if I'm going down the wrong way, is that I don't know how to pass back the model back to the Controller Action from the Ajax submit. When I look at Telerik's code, it looks like they store the persisted items in HttpContext.Session, and this is exactly the reason why I don't want to use their grid.
Thanks.
They might choose the session repository storage for demonstration purposes. If you transform the logic from their SessionProductRepository class for your model and implement identical Update/Insert/Delete methods for it, you'll probably get what you want.

Add controls dynamically on button click in asp.net mvc

I am creating an asp.net MVC application in which I want to provide a functionality to add a controls dynamically. I have a form in which there are 2 text boxes for First Name and Last name which serve as a single control. Now an user can add any number of this group of controls. I am able to add these controls on the page using java script. But I do not know how to access the values of these control when the user submits.
Please help in this or suggest another approach
Thanks
Look at using a Jquery AJAX call for the submit operation.
You can interate through your controls (easy with jquery class selector and $.each) and push the variables into a js variable.
Parse it as JSON and pass the data back to the controller using the ajax call..
Have a read of the article Editing a variable length list, ASP.NET MVC 2-style by Steve Sanderson. It shows you how to do what you are looking for in a clean, MVC style.
If you're coming from a webforms perspective, you're accustomed to adding those new controls programmatically in the codebehind. Using ASP.NET MVC, you're better off doing this with javascript.
It should be trivial to write a javascript function that adds FirstName1, FirstName2, FirstName3, etc. In the Controller, inspect the Request.Form.AllKeys to determine how many fields were added by the user.
You could also iterate a number in a hidden field called "txtNumFields", then use that as your controlling value in a for loop:
int numFields = int.Parse(Request.Form["txtNumFields"]);
for (i==0;i<numFields ;i++)
{
string firstName = Request.Form["FirstName" + i.ToString()];
...
}

ASP.NET MVC 2 AJAX dilemma: Lose Models concept or create unmanageable JavaScript

Ok, let's assume we are working with ASP.NET MVC 2 (latest and greatest preview) and we want to create AJAX user interface with jQuery. So what are our real options here?
Option 1 - Pass Json from the Controller to the view, and then the view submits Json back to the controller. This means (in the order given):
User opens some View (let's say - /Invoices/January) which has to visualize a list of data (e.g. <IEnumerable<X.Y.Z.Models.Invoice>>)
Controller retrieves the Model from the repository (assuming we are using repository pattern).
Controller creates a new instance of a class which we will serialize to Json. The reasaon we do this, is because the model may not be serializable (circular reference ftl)
Controller populates the soon-to-be-serialized class with data
Controller serializes the class to Json and passes it the view.
User does some change and submits the 'form'
The View submits back Json to the controller
The Controller now must 'manually' validate the input, because the Json passed does not bind to a Model
See, if our View is communicating to the controller via Json, we lose the Model validation, which IMHO is incredible disadvantage. In this case, forget about data annotations and stuff.
Option 2 - Ok, the alternative of the first approach is to pass the Models to the Views, which is the default behavior in the template when you start a new project.
We pass a strong typed model to the view
The view renders the appropriate html and javascript, sticking to the model property names. This is important!
The user submits the form. If we stick to the model names, when we .serialize() the form and submit it to the controller it will map to a model.
There is no Json mapping. The submitted form directly binds to a strongly typed model, hence, we can use the model validation. E.g. we keep the business logic where it should be.
Problem with this approach is, if we refactor some of the Models (change property names, types, etc), the javascript we wrote would become invalid. We will have to manually refactor the scripting and hope we don't miss something. There is no way you can test it either.
Ok, the question is - how to write an AJAX front end, which keeps the business logic validation in the model (e.g. controller passes and receives a Model type), but in the same time doesn't screw up the javascript and html when we refactor the model?
Stick with Option 2, but there are ways to test the code. You can use a web application testing tool like WatiN or Selenium to perform integration tests on your HTML pages. Also, FireUnit gives you the ability to unit test your JavaScript code (you'll need Firefox and Firebug in order to use it).
In the spirit of full disclosure, I haven't tried out MVC 2 yet. However, I've been using MVC 1 for some time now and have used these tools with some pretty good results.
Problem with this approach is, if we
refactor some of the Models (change
property names, types, etc), the
javascript we wrote would become
invalid.
I dont see how changing a property of the model changes javascript-code. Usually you hijack the submit event of a form and submit it via ajax. No properies envolved, a long as you take option 2.
Changing properties might break your MVC - application, but thats not specific to ajax.

Resources