How to dynamic bind html.DropDownList() in MVC

2019-06-13 06:15发布

I have a dropdownlist and a textbox in my page,I want to change the dropdownlist with the textbox change. I use JQuery post like this:

$("#txtBuildId").change(function() { var builddate = $("#txtBuildId").val(); $.post("/UTOverview/Index?builddate=" + builddate); });

and my Index function is:

public ActionResult Index()
    {
        string buildDate = Request.Params.Get("builddate");
        DataTable tbBuildid = DatabaseService.getBuilidByDate(buildDate);
        List<SelectListItem> list = new List<SelectListItem>();
        foreach (DataRow bd in tbBuildid.Rows as IEnumerable)
        {
            list.Add(new SelectListItem { Text = bd["buildid"].ToString(), Value = bd["buildid"].ToString() });
        }
        ViewData["tbbuildid"] = list;
        return View();
    }

But I found that the dropdownlist didn't change with the DataView["tbbuildid"] change? Why ?

I try to do this via full postback way like: window.location = "/UTOverview/Index?builddate=" + builddate; It works. ViewData["tbbuildid"] changed every time I post the new builddate to the method index.But how can I do this by Ajax way?

3条回答
我命由我不由天
2楼-- · 2019-06-13 06:56

Did you try debugging your cs code and adding alerts in your javascript code.

Try doing these you should get closer to the actual problem also post these findings in your question.

查看更多
对你真心纯属浪费
3楼-- · 2019-06-13 07:15

The jquery .post() is actually an asynchronous call to the server. It returns some data which you then need to do something with.

If you simply want to refresh your page via a full postback, you could do

window.location = "/UTOverview/Index?builddate=" + builddate;

If you want to alter the state of your dropdown dynamically, without a page refresh, you will need to pass a callback to .post() which updates your drop down box based on the returned data. In which case, you don't want to have it call your index action, but a specific action for retrieving updated data. Something such as:

$.post("/UTOverview/BuildSelect?builddate=" + builddate, function(data) {
  $('#buildDropDown').html(data);
});

See jQuery.post() for more info. Or rather than constructing the HTML in the controller action, which is a bit of a no-no, return a Json result and bind your drop down to this.

In both cases, be aware that listening for the onchange event will only fire when the textbox loses focus.

查看更多
叼着烟拽天下
4楼-- · 2019-06-13 07:17

In your Action method, you are returning a View, But do you have a view for this ? In this case, I would simply return Json from the action method.

Just return Json from your Action method and use that to populate your dropdow. Since you are making an Http Post call, It will hit your HTTPPost Action method

[HttpPost]
public ActionResult Index()
{
        string buildDate = Request.Params.Get("builddate");
        DataTable tbBuildid = DatabaseService.getBuilidByDate(buildDate);
        List<SelectListItem> list = new List<SelectListItem>();
        foreach (DataRow bd in tbBuildid.Rows as IEnumerable)
        {
            list.Add(new SelectListItem { Text = bd["buildid"].ToString(), Value = bd["buildid"].ToString() });
        }
        return Json(list);
}

And in your script,

    $("#txtBuildId").change(function () {
        var builddate = $("#txtBuildId").val();
        $.post("@Url.Action("Index","UTOverview")", {builddate:builddate},function(data){
          $.each(data, function() {
                $("#select1").append($("<option />").val(this.Value).text(this.Text));
         });
        }); 
     });

It is always a good practice to use Url.Action HTML helper to get the path to the Action method as MVC will take care of returning the correct path to the action method. You dont need to worry about how many ../ to use.

The above code is tested and it will work fine.

查看更多
登录 后发表回答