I have a sample application in Asp.Net MVC 4. I don't find the way to obtain the selected id from the DropDownListFor helper and assign it as parameter to an ActionLink.
Here is my models:
public class EmpresaLibroViewModel
{
//property a usar en vista Index ya que son iterables
public IEnumerable<EmpresaModel> Empresas { get; set; }
public IEnumerable<BancoModel> Bancos { get; set; }
public IEnumerable<LibroModel> Libros { get; set; }
//property que van a contener solo un registro (para Detalles, Editar)
public EmpresaModel Empresa { get; set; }
public BancoModel Banco { get; set; }
public LibroModel Libro { get; set; }
}
Here is the Edit method where I want to obtain the selected Banco ID and send as parameter to the ActionLink:
@model MvcApplication1.ViewModels.EmpresaLibroViewModel
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>EmpresaModel</legend>
@Html.HiddenFor(model => model.Empresa.EmpresaModelID)
<div class="editor-label">
@Html.LabelFor(model => model.Empresa.Nombre)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Empresa.Nombre)
@Html.ValidationMessageFor(model => model.Empresa.Nombre)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Empresa.Cuit)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Empresa.Cuit)
@Html.ValidationMessageFor(model => model.Empresa.Cuit)
</div>
<h3>Tiene libros en:</h3>
<table>
@foreach (var unitem in Model.Libros)
{
<tr>
<td>
@unitem.Bancos.Nombre (empresa:@unitem.EmpresaModelID - banco:@unitem.BancoModelID)
@Html.ActionLink("(eliminar)", "DesvincularBanco", new { id = unitem.LibroModelID, idEmp = unitem.EmpresaModelID })
</td>
</tr>
}
</table>
<h3>Agregar:</h3>
@Html.DropDownListFor( model => model.Banco.BancoModelID , new SelectList(Model.Bancos, "BancoModelID", "Nombre")))
@Html.ActionLink("(agregarlo)", "VincularBanco", new { idempresa=Model.Empresa.EmpresaModelID , idbanco=10 } )
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
What is the best way to do it? Thanks.
Note: the idBanco=10 has set to verify that working the ActionLink. I know that that value must be from the DropDownListfor.
With the help of jquery you can do it easily.
First, add an id to your actionlink:
@Html.ActionLink("RegisterModules", "Home", new { idempresa =5, idbanco = 10 }, new { id = "myLink" })
Now add the script to your view ( I would prefer adding it to a javascript file and bundle the file and add to this page) :
<script type="text/javascript">
$(document).ready(function () {
$('select[id*="Banco"]').change(function () {
var lnk = $('#myLink').attr('href');
var givenval = $('select[id*="Banco"]').val();
var result = lnk.split("idbanco=")
if (result.length > 1) {
lnk = result[0] + "idbanco=" + givenval;
}
$('#myLink').attr('href', lnk);
});
});
</script>
And make sure that jquery is added to this page. And you are done!