ASP.NET MVC reading an element's custom html attribute when submitting - asp.net-mvc

I'm new to ASP.NET and MVC in particular.
Now, I'm trying to understand if I can easily get values of custom attributes of submitted data.
For example, When writing something like this inside a form (which works and posts and I can get the checkbox value)
<%= Html.CheckBox("cb1", new { listen = "listen:6" }) %>
Can I get the value of "listen" directly or do I need JS?
(I know I can just use hidden fields, but I'm I'm asking anyway)
Thanks

You cannot; when a form is POST-ed, only the name/value pairs are sent. This is a general feature of HTML and forms, and not specific to ASP.NET or MVC.

Related

Why are my dotnet 5.0 mvc form fields retaining their input values on post?

I have an dot net 5.0 mvc page which takes a model object (ClassFoo) which when constructed generates an instance of (classBar). ClassBar has various properties (FieldA, FieldB, FieldC) all are strings.
The Views content is all in a form and the form's input fields are all from ClassFoo.ClassBar's various properties. Initially, when the page is accessed, all form input values are empty. However when I put data into them and then submit the form, the form values are still there when the page loads. However I don't understand why this is because I'm explicitly creating a new model during the controller operation but I am not actually populating the Model.ClassBar with the content from the post before I return model to the View for generation.
What I would expect is that all of the form fields would be empty however that is not the case. I know if asp.net the form values are stored and restored automatically but I didn't think that happened in mvc.
After looking into ModelState recommended by Nick Albrech in the comments I reviewed the hint associated w/ the HtmlHelper.TextBoxFor() which states the following:
... Adds a "value" attribute to the element containing the first non-null value found in: the ActionContext.ModelState entry with full name, or the expression evaluated against ViewDataDictionary.Model. See [IHtmlHelper.NameFor] for more information about a "full name".
So effectively what's happening is similar to what I thought asp.net mvc wasn't doing in that it populates the ModelState from a get/post request with the name and values of the form being submitted. Then based on the use of these helper functions (and also asp-for attributes used in razor views views), it either provides values from the saved model state form values OR the model passed to the view. Note: this does not seem to work if you set the value of an input element = #Model.[someProperty]
The take away from this is that you do not necessarily need to update your model object with content from the previous form submit in order to have the page populate the form contents back to the screen. Allow asp.net mvc to do the manual tasks by making use of these razor helpers.
Shoutout to Nick for the assist on this one. A solid member of the stackOverflow community.

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.

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()];
...
}

What is the proper way to handle forms in ASP.NET MVC?

Forms + ASP.NET MVC = Confusing for me:
What are the preferred ways to setup your controller action for form posts?
Do I need to specify an attribute that has [AcceptVerbs(HttpVerbs.Post)]?
Should the controller action take a "FormCollection" or should I use ModelBinders?
If I should use ModelBinders, how?
How do I setup the form in the view?
Should I use the Html helpers like Html.BeginForm/Html.EndForm or simply specify the form tag myself?
How do you specify the controller and action to be used in a form (with either the Html helpers or with a manual form tag)?
Can somebody please show me both a simple view with a form ~and~ its corresponding controller action?
I'm trying to write a form with a single textbox that I can submit to the Home/Create action and pass the string from the textbox to it.
ScottGu's handling form edit and post scenarios is exactly what you're looking for. There's also form posting scenarios and even though it was written for preview 5, it's still mostly valid.
The template's AccountController.LogOn and .Register methods along with the corresponding views should give you the simple introduction you need.

Naming of ASP.NET controls inside User Controls with 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.

Resources