Asp.net MVC Selected Index Changed / Ajax.ActionLi

2019-08-20 04:47发布

问题:

I have a page in Asp.Net MVC using the Razor syntax. In the page I have a DropDownList, and a DIV section that I would like to replace the content in the DIV depending on the selected value of the combobox using the Ajax.ActionLink functionality

Is there a way to do this?

Thanks

Mark

回答1:

I would rather use a form than a link as it is more adapted to what you are trying to achieve:

@using (Ajax.BeginForm(
    "Change", 
    "Home", 
    new AjaxOptions { UpdateTargetId = "result" }
))
{
    @Html.FropDownListFor(x => x.Foo, Model.Foos, "-- Select a foo --")
    <input type="submit" value="Change" />
}

<div id="result"></div>

And the corresponding controller action:

public ActionResult Change(string foo)
{
    string view = ... // select the partial based on the selected value
    return PartialView(view);
}


回答2:

you can use jquery to call your ajax action

  function OnDddlChanged() {
    $.ajax({
        url: "controller/action/"+$("#SelectTagID").val(),
        dataType: 'html',
        type: 'Get',
        success: function (r) {
            $('#DivID').html(r);
        },
        error: function () {
            alert('Error');
        }
    });
}

mvc ajax action will like that

 public MvcHtmlString MyAction(string id)
{
  if(Request.IsAjaxRequest)
  {
    //return your html as MvcHtmlString
  }
}