Vincentw Vincentw - 3 months ago 23
ASP.NET (C#) Question

Databind editorfor with dropdown

I am trying to find out if it is possible to bind the HTML Helpers to a dropdownlist.

For example, I have the following model:

public class CrmViewModel : ViewModelBase
{
[Display(Name = "LBL_BEDRIJFSNAAM", ResourceType = typeof(Properties.Resources))]
public string Bedrijfsnaam { get; set; }
public IQueryable<ContactPerson> contactPersons { get; set; }

}

public class ContactPerson
{
public GenderEnum Gender { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Initials { get; set; }
public DateTime DateOfBirth { get; set; }
public string EmailAddress { get; set; }
public string PhoneNumber { get; set; }
public string Label { get; set; }
}


This gets pushed back to the page as an IQueryable

Now what I want to do, is edit in an dropdownlist with the name of the contactperson, when someone select a contactperson, I want that information to be filled in into the Html.EditorFor values that exist so I can post this back to the controller.

So for example if someone selects the user Foo Bar, I want the value foobar@foo.com to be entered at the email address.

Is this possible without resorting to something like KnockoutJS?

Answer

I have create a smaller vm for this sample like this:

CrmViewModel

 public class CrmViewModel
 {
        public string Bedrijfsnaam { get; set; }
        public IQueryable<ContactPerson> contactPersons { get; set; }
  }

ContactPerson

public class ContactPerson
{
        public string FullName { get; set; }
        public string Email { get; set; }

        public override string ToString()
        {
            return FullName;
        }
}

I have created a small sample page as follows:

@model WebApplication4.Models.CrmViewModel
@{
    ViewBag.Title = "Index";
}



<h1>@Model.Bedrijfsnaam</h1>

@Html.DropDownListFor(m => m.contactPersons,
    new SelectList(Model.contactPersons,
    Model.contactPersons.First().FullName), new { @onchange = "CallChangefunc(this.value)" })

<br />
@Html.LabelFor(m => m.contactPersons.First().FullName)
<br />
<span id="fullname">
    @Html.DisplayFor(m => m.contactPersons.First().FullName)
</span>
<br />
@Html.LabelFor(m => m.contactPersons.First().Email)
<br />
<span id="email">
    @Html.DisplayFor(m => m.contactPersons.First().Email)
</span>

So now we need a way to perform some action when the 'onchange' event is triggered. We can do this as follows:

JS

<script>
    function CallChangefunc(value) {
        $.ajax({
            url: '/Home/Fill',
            type: "GET",
            dataType: "JSON",
            data: { fullName: value },
            success: function (contactPerson) {
                document.getElementById("fullname").textContent = contactPerson.FullName;
                document.getElementById("email").textContent = contactPerson.Email;
            }
        });
    }
</script>

In the above JS we do a call to some controller action to fetch the contact information we need to retrieve for the selected contact person. When the JSON is returned we get the span and change the textContent to the right value.

Controller Action

public ActionResult Fill(string fullName)
        {
            ContactPerson contactPerson = new ContactPerson();
            if (fullName == "Richard Hendricks") //Replace this with call to the database in order to get your contact info
            {
                contactPerson = new ContactPerson
                {
                    FullName = "Richard Hendricks",
                    Email = "r.hendricks@piedpiper.com"
                };
            }
            else if (fullName == "Erlich Bachman")
            {
                contactPerson = new ContactPerson
                {
                    FullName = "Erlich Bachman",
                    Email = "e.bachman@piedpiper.com"
                };
            }
            return Json(contactPerson, JsonRequestBehavior.AllowGet);
        }

In the controller action, we get the data from our database. In the sample above its an if statement but this would be the something like var contactPerson = db.ConactInfo.SingleOrDefault(c=>c.FullName == fullName); if you are using EF for example.

In this example, we are using the full name but in a real world use case we would use a unique value like the email address for example.

Result enter image description here