Is there any way to call JavaScript in an MVC4 ActionLink for one of the RouteValue parameters?

StackOverflow https://stackoverflow.com/questions/15104025

Pergunta

I have a drop down list (DropDownListFor) and an ActionLink on my page. Basically, the problem I'm having is I'm trying to capture the selected value from my drop down list and passing that into my ActionLink as an ID. Here's my code:

@Html.DropDownListFor(x => x.Capsules, new SelectList(Model.Capsules, "pk", "name", "pk"))
<br />
@Html.ActionLink("Submit", "Create", 
    new { controller = "Process", id = /*JavaScript here to get the selected ID for the DropDownList above*/ },
    new { data_role = "button" })

For what I'm trying to accomplish, is there a way to embed JavaScript into my Html.ActionLink call? If there's not a way, or if it's not recommended, could you please advise of another solution to solve this problem? Thanks in advance!

Foi útil?

Solução

You can do this via intercepting the link using javascript Darin has posted an example of this.

However, it looks like you're trying to submit some values using an ActionLink, and you're probably better off creating a viewmodel which holds all the values you want, and then posting everything using a submit button. This allows you to post more data than just the ID, prevents you from being dependent on Javascript, and keeps all of the code server side instead of mixing and matching.

Judging by the small code you've posted - you already have a model, probably some strongly typed entity, and it has a property called Capsules.

In your controller, create the view model which holds the view's data:

public class YourViewModel
{
   YourModel YourModel { get; set; }

   public int CapsuleId { get; set; }
}

Then your view:

@using( @Html.BeginForm( "Create", "Process"  ) )
{
@Html.DropDownListFor(m=> m.CapsuleId, new SelectList(Model.YourModel.Capsules, "pk", "name", "pk"))
<input type="submit">
}

Then your controller action to handle this:

[HttpPost]
public ActionResult Create( YourViewModel model )
{
   var id = model.CapsuleId;

  // do what you're going to do with the id
   return View();
}

Outras dicas

You can put dummy value for the id parameter like this :

@Html.ActionLink("Submit", "Create", 
    new { controller = "Process", id = "dummy" },
    new { data_role = "button" })

Then replace that value when the link is clicked.

// Assuming your link's id is `submit`, and the dropdown's id is `capsules`
$('#submit').click(function() {
    var id = $('capsules').val();
    $(this).href = $(this).href.replace('dummy', id);
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top