Call an action in dropdownlist changed and send a model to view

1.5k views Asked by At

I'm trying to call a control action in dropdownlist selected item changed and i do it using jquery:

  @Html.DropDownListFor(model => model.SelectedItemType.RowId, new SelectList(Model.ItemTypes, "RowId", "ItemTypeName")
                , htmlAttributes: new { @class = "form-control SelectList",@id="itemTypesDropDown", style = "height:300px", @size = 5
                }))

And

 $("#itemTypesDropDown").change(function () {
        var selectedValue = $('#itemTypesDropDown').val();
        $.post('@Url.Action("Select", "Home")', { selectedRowId: selectedValue }, function (data) {
        });
    }); 

and the control action is:

  [HttpPost]
    public ActionResult Select(long selectedRowId)
    {
        SetIndexViewDatas();

        var itemtypemodel = new ItemTypeViewModel
        {
            ItemTypes = _db.Inv_ItemType.Select(x => x).ToList(),
            SelectedItemType = _db.Inv_ItemType.FirstOrDefault()
        };
        return View("Index", itemtypemodel);
    }

and index.cshtml:

  <div class="row">
        <div class="form-group verticalAlign">
            @Html.LabelFor(model => model.SelectedItemType.ItemTypeName, "Attribute Name", htmlAttributes: new { @class = "control-label col-md-4 lable" })
            <div class="col-md-8">
                @Html.EditorFor(model => model.SelectedItemType.ItemTypeName, "Attribute Name", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.SelectedItemType.ItemTypeName, "", new { @class = "text-danger" })
            </div>
        </div>
        <br />

It works fine,after selected item changed it callsselect action and post itemtypemodel to index view,but the problem is it doesn't load data in the index,where am i doing wrong?

1

There are 1 answers

8
AudioBubble On BEST ANSWER

You making an ajax call, which means you stay on the same page. Your method needs to return a partial view, and really should be a GET. Then you need to update the DOM with the html your returning

public ActionResult Select(long selectedRowId)
{
    ....
    return PartialView("Index", itemtypemodel);
}

In the view, include an element as a placeholder to render the partial view you return

<div id="myContent"></div>

and modify the script to

$("#itemTypesDropDown").change(function () {
    $.post('@Url.Action("Select", "Home")', { selectedRowId: $(this).val() }, function (data) {
        $('#myContent').html(data);
    });
});

Alternatively, if you do not want to update the current page, but instead want to redirect to another page, do not use ajax (just use a normal submit and redirect).