views:

1834

answers:

2

Hi, I'm new to ASP .NET MVC and to web programming in general.

I'm wondering if there is a way to set ViewData variables when a radiobutton is selected -- but before the page is submitted.

Maybe I'm barking up the wrong tree but what I'm trying to do is create a form where new fields are added based on which radio button is selected. So what I want to do is when a radiobutton is clicked it sets a ViewData variable and based on that ViewData variable a different partial view loads the appropriate fields below the current field.

I imagine there must be someway of doing a onclick="some C# function that sets ViewData(args)"

Thanks

+1  A: 

ViewData only exists, and only exists server-side, for the lifetime of the request. So, once the page is rendered the object no longer exists.

Some alternate approaches you can take:

1 - Use client-side Javascript to add a form and inputs as necessary. More info here: http://stackoverflow.com/questions/463644/asp-net-mvc-jquery-dynamic-form-content

2 - Pre-render the new form, but hide it via CSS, and unhide it when the appropriate radio button is clicked. More info here: http://stackoverflow.com/questions/458466/expand-collapse-html-field-firefox

3 - Use AJAX to render the new form when the appropriate radio button is clicked. More info here: http://www.asp.net/learn/mvc/tutorial-32-cs.aspx

RedFilter
+1  A: 

There are a couple of ways you could go about this.

1) You could have an Ajax form where through Javascript you post the form back and check to see if it's an Ajax Request, there by returning a partial view to a div that you specify.

2) Post the form as is and check server-side to see if the radio button was clicked, and thus redisplay the form with the new options visible.

If you take the first approach it would be easy enough to fall through to the second one for those without Javascript enabled.

There aren't really "onclick" events as I'm assuming you are used to from Webforms, you would basically have to roll your own Javascript to handle such things. Once you do a few, I think you'll find it's really not too bad, with the benefit that you'll have more control over what you're doing and through that gain a better understanding of the larger picture.

dhulk