我有一个下拉列表需要触发一个带有已点击的id值的Url.Action
目前我有: 模型
using System.Collections.Generic;
using System.Data.Entity;
using System.Web.Mvc;
namespace Portal.Models
{
public class CompanyViewModel
{
public int Id { get; set; }
public string CompanyName { get; set; }
public IEnumerable<SelectListItem> CompaniesList { get; set; }
}
public class CompanyViewModelDbContext : DbContext
{
public DbSet<CompanyViewModel> Contacts { get; set; }
}
}
查看
@model Portal.Models.CompanyViewModel
@{
ViewBag.Title = "ShowDropdown";
}
@Html.DropDownListFor(m => m.Id, new SelectList(ViewBag.CompanyList as System.Collections.IEnumerable, "CoId","CompanyName"), Url.Action("SelectCompany", "Home", new { partnerCoId = "CoId" }, null))
控制器方法
public PartialViewResult ShowDropdown()
{
var coid = Lt.GetThisUsersCoId();
var model = new CompanyViewModel();
using (var dc = new CompanyViewModelDbContext())
{
var content =
(from cr in db.CompanyRelationship
//This is grabbing all related companies to the logged in user
join c in db.Companies on cr.CoId equals c.CoId
where cr.PartnerCoId == coid
select new
{
cr.CoId,
c.CompanyName
}).Distinct().ToList();
ViewBag.CompanyList = content;
foreach (var item in content)
{
model.Id = item.CoId;
model.CompanyName = item.CompanyName;
}
}
return PartialView(model);
}
public ActionResult SelectCompany(int partnerCoId, string redirect)
{//Bunch of code that I didn't write but just needs to be triggered on click
下拉列表应根据全局值列出一堆公司,选择一个公司后会建立关系。
我想要完成的任务:根据从下拉列表中选择的内容触发ActionResult SelectCompany。目前它似乎没有做任何事情,是否有任何好的调试工具我应该在VS中使用,看看当我点击下拉菜单时会发生什么。从我的前端看,当我选择一家公司时似乎没有任何反应。
更新 我已经将脚本调用放入我的View中,但是我在使用@ url.Action时遇到了问题,我必须通过这个:
@Url.Action("SelectCompany", "Home", new {partnerCoId = x})
从下拉列表中选择的值。
答案 0 :(得分:1)
您可以使用下拉列表的JQuery Change()
事件。
实现这一目标的最简单方法是:
将以下代码放在您的视图中:
@Html.DropDownListFor(m => Model.Id, new SelectList(ViewBag.CompanyList as System.Collections.IEnumerable,"Select", new { @id = "dropdwonId" })%>
<script>
$("#dropdwonId").change(function() { // This will fire when the dropdown value will get changed
var url = "YourUrl/" + $(this).val(); //Append Id To URL
window.location.replace(url);
});
</script>