Llevo un rato dandole la vuelta a esto y no he conseguido tomar el value de un dropdownlistfor desde mi javascript, estoy comenzando con los viewcomponents en MVC Net Core.
Desde ya, gracias.
Creo un DropDownListFor de la siguiente manera:
@model SubCompanyModel
@using (Html.BeginForm(FormMethod.Post))
{
@Html.DropDownListFor(n => n.SelectedSubCompanyId, Model.SubCompanies, Resource.GeneralSelectText)
}
Mediante el siguiente viewcomponent
public class DropDownCompanyViewComponent : ViewComponent
{
private AppSettings AppSettings { get; set; }
public DropDownCompanyViewComponent(IOptions<AppSettings> settings)
{
AppSettings = settings.Value;
}
public IViewComponentResult Invoke()
{
ServCliCostCenter.Client client = new ServCliCostCenter.Client(new System.Net.Http.HttpClient()) { BaseUrl = AppSettings.UrlAPIBackCostCenters };
ICollection<ServCliCostCenter.SubCompany> subCompany = client.GetSubCompanyAsync().GetAwaiter().GetResult().Values;
var model = new SubCompanyModel
{
SubCompanies = new SelectList(subCompany, "IdSubCompany", "SubCompanyName", 1)
};
return View(model);
}
}
Eso me genera el siguiente form:
<form action="/" method="post"><select data-val="true" data-val-required="The SelectedSubCompanyId field is required." id="SelectedSubCompanyId" name="SelectedSubCompanyId"><option value="">Please select an order template</option>
<option value="1">TEST1</option>
<option value="2">TEST2</option>
<option value="3">TEST3 </option>
</select><input name="__RequestVerificationToken" type="hidden" value="CfDJ8BLIbwwZ-LhAu_z4M8SoNFH9ecLEYtBRuUd8OidqIkuKds_93ubTjvJsaLmNkAByqfGCivXgezOQDBegEYv7k9Tm_qScPnyEC0y0GL5c0QAtuLR5ne5Cs1j2vOlpdLZqKyM9ZhuvLAO1Yb0Sf6fpTxU"></form>
Lo que quiero hacer y no he logrado, es obtener el value del select mediante javascript, lo he intentado de la siguientes maneras:
var e = document.getElementById("SelectedSubCompanyId");
var strUser = e.options[e.selectedIndex].value; //SELECTED INDEX SIEMPRE VIENE EN 0
var subCompanyId = $('#SelectedSubCompanyId').val(); //SIEMPRE TRAE EL VALUE 1