1

When I post via the click on "btSave", in the controller I receive the model. In the model, I see the value off all fields (I show here only "FirstName" but there are others). But the doropdownlist value are null all the time.

Do you have an idea why ?

Thanks,

//Dropfown content
public class LkpTypeCompany
{
    public virtual int Id { get; set; }
    public virtual int Code { get; set; }
    public virtual string NL { get; set; }
    public virtual string FR { get; set; }
    public virtual string Value { get; set; }
}

//Model Definition
public class CustomerModel
{
    public List<LkpTypeCompany> LkpTypeCompany { get; set; }
    public Customer Customer { get; set; }
}

//Posting form
jQuery('#btGeneralSave').click(function (event) {
    var jqxhr = $.post("Controller/Actio,", $("form").serialize(),
    function (data) {
    });
});

//HTML
@model eSIT.GC.WebUI.Models.CustomerModel
@using (Html.BeginForm())
{
    @Html.TextBoxFor(m => m.Customer.FirstName, new { maxlength = 50 })
    @Html.DropDownListFor( m => m.Customer.LkpTypeCompany, new SelectList(Model.LkpTypeCompany, "Code", "FR", Model.Customer.LkpTypeCompany.Code))
    <input type="button" id="btSave" value="Save"/>
}
1

1 Answer 1

1

I see the overload that you were attempting to use but I have had good luch with using SelectListItem

Try

 @Html.DropDownListFor( m => m.Customer.LkpTypeCompany, 
     new SelectList(Model.LkpTypeCompany
                         .Select(i => new SelectListItem
                                      {
                                        Text = i.Code, 
                                        Value = (*somecondition*) ? i.FR : i.NL, 
                                        Selected = i.Code == Model.Customer.LkpTypeCompany.Code
                                      }));
Sign up to request clarification or add additional context in comments.

4 Comments

I have some remarks : 1. I'd like avoid Linq or other C# code in cshml page; 2. I have an error on "SelectedListItem"; 3. it's not FR, it's may be FR or NL depending of the user language, the "FR" or "NL" text will be copy in "Value" field
@Kris-I it was a typo, it's actually SelectListItem and not SelectedListItem. I'm not sure how you can conditionally switch b/w FR and NL without linq. See my edit, and fill out the condition to determine if you want to use FR or NL.
Linq ok but no link in cshtml page. With your code in the dropdown I have this "<option>System.Web.Mvc.SelectListItem</option>" no value for the option. At this time I use "DropDownList" with a jquery post (get selected value with jQuery)
considering that the answer in for 8 years ago, is it still the best solution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.