View 2 dataTextField in a Selectlist

Asked

Viewed 134 times

4

Hello! I have a little problem to make a selectlist display 2 values in textfield. I have the following Selectlist which is stored in a viewbag:

ViewBag.Account = new SelectList(new AccountBusiness().GetList<Account>(Util.AuxiliaryMethods.BMPerRequestInstance).ToList(), "AccountId", "AccountNumber");

In the DOM it displays the Accountnumber in the Option text and the Accountid in its value. On the screen it displays as follows:

inserir a descrição da imagem aqui

I need it to display instead of just Accountnumber, also display one more field, which is Description, so it would be Accountnumber + Description, more or less like "15252 - Standart", and no value would continue to return Id. How can I make the Selectlist receive two parameters ?

  • 1

    Could concatenate the property Description with a separator and after obtaining the value made a split by the separator character (can be "-" or ";").

  • The value that would be the Id I already got by the option Value, so the text I put in the option will not make a difference. So I guess I wouldn’t have to split to get it later, is that I’m getting the id by javascript. But about concatenating, I do it before sending to selectlist or after ?

  • 1

    I think it would be in the SelectList directly.

  • But how would he do it ? I tried to get him to pass type 2 fields, using + "-" + but he understands it as if it were the name of the field. If I play "Accountnumber" + "-" + "Description" it looks exactly for that field. I don’t know much about concatenation as you can see Uahua if you can help me with example code

1 answer

2


Just you popular your SelectList() with a List<SelectListItem> or compose another object with structure providing the values that will be used for the properties Value and Text.

var selectAccounts = new AccountBusiness()
                            .GetList<Account>(Util.AuxiliaryMethods.BMPerRequestInstance)
                            .Select(x => new { Value = x.AccountId, Text = string.Format("{0} - {1}", x.AccountNumber, x.Description})
                            .ToList();
ViewBag.Account = new SelectList(selectAccounts, "Value", "Text"));
  • Ha, I was just gonna say that :)

  • Thank you brother ! He in this case returned it in the dropdownlist "{ Value = 1, Text = 15252 - Standart }" but it works, takes the Description and the Accountnumber, I’ll just see a way to play the value in the value of the option. Thanks bro!

  • Look at my edition, I think it’s clearer now.

  • I had forgotten to declare the attributes, since I used a simple object and not the type SelectListItem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.