views:

53

answers:

3

I have a form to which I want to add extra fields depending on the value of a dropdown list. They would be sets of fields and I was thinking on dynamically changing a div's content with the html from a render partial, which would render a PartialView with the fields I want.

Right now the code for the drop down list is the following

    <p>
        <label for="CatalogItem.Type"> Type: </label>
        <%=Html.DropDownList("CatalogItem.Type",Model.Types, "Choose Type") %>
    </p>

    <div id = "ExtraInfo">

    </div>

And I want to put the extra stuff (fields specialized for the type) in the ExtraInfo div. What would the jQuery code be for this?

Thanks!

+1  A: 

First add a css class selector to your dropdown, lets call it 'mydropdown' for now

use something like this:

<script language=”javascript” type=”text/javascript” >

      function addtoDiv()
        {
        $(document).ready(function() {

        var myval=$(”#mydropdown”).val(); // get value of dropdown


        if ( myval == "somevalue") // check myval value
        {
            $("#ExtraInfo").html("add html code inside div here"); // add code based on         value
        }

        }}
  </script>
Tony
+3  A: 

@Tony has the right approach but instead of putting your RenderPartial html right into the ".html("add html code inside div here")" you may want to do an ajax call. That way the user isn't downloading a bunch of html he/she may not even see.

something like so:

if ( myval == "someValue")
{
    $("#ExtraInfo").load("/dynamic-stuff/1")
}
else if ( myval == "someOtherValue")
{
    $("#ExtraInfo").load("/dynamic-stuff/2")
}

This also assumes you have a route set up to handle a url like "/dynamic-stuff/2" and responds with the correct partial view.

DM
A: 

Hey,

Do you need to dynamically add fields? You can add fields with JQuery by doing:

$("").attr("id", "test").addClass("FormLabel").appendTo("#parentElement"); $("").attr("id", "testinput").attr("type", "text").appendTo("#parentElement");

In this way, you can create the fields programmatically.

As an alternative, you can create a JQuery partial view. Create an action method that returns an instance of this partial view, and call that action method using

$.get("/<controller>/<actiontoreturnpartialview>", function(data) {
   $("#ExtraInfo").html(data); 
});

It makes it easier because then you can rely on server-side logic to render the UI, though I tend to use the client-side approach.

Alternatively, you can create your own HTML helper to do this all, but that would be a lot of work.

HTH.

Brian