我有一个MVC3应用程序,它从模型中填充下拉列表。当我从列表中选择一个项目时,我想在单个“编辑”链接上更新网址('/Edit/4')
,这将允许我显示编辑视图,即不使用为所有记录创建编辑链接的模板在模型中,我想使用一个编辑链接,然后在下拉列表中选择项目时更新它。我已经能够使用jquery实现其中一些,我想在使用MVC的C#代码中实现。
有什么想法吗?
答案 0 :(得分:3)
我创建了一个示例代码。我有一个区域。突出显示的部分是您关注的代码。
public class DropdownController : Controller
{
[HttpGet]
public ActionResult DropDownListFor()
{
Practise.Areas.MyPractise.Models.Dropdown d = new Models.Dropdown();
return View(d);
}
public ActionResult Edit(string Val)
{
return View();
}
}
public class Dropdown
{
[Required(ErrorMessage = "Please select state")]
public string StateId { get; set; }
public int MyProperty { get; set; }
public List<SelectListItem> States
{
get
{
return new List<SelectListItem>()
{
new SelectListItem
{
Text = "Punjab",
Value = "Pb",
Selected = false
},
new SelectListItem
{
Selected = false,
Value = "HM",
Text = "Himachal"
}
};
}
}
}
@model Practise.Areas.MyPractise.Models.Dropdown
<!DOCTYPE html>
<html>
<head>
<title>DropDownListFor</title>
<script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#StateId').change(function () {
if($('#StateId option:selected').val() == "")
$('.edit').attr('href', "#");
else
$('.edit').attr('href',
"@Url.Action("Edit", "Dropdown",
new RouteValueDictionary(new { area = "MyPractise" }))"
+ "/" + $('#StateId option:selected').text());
});
});
</script>
</head>
<body>
@using (Html.BeginForm("DropDownListFor", "DropDown", FormMethod.Post,
new { id = "DropDownList" }))
{
@Html.DropDownListFor(m => m.StateId, Model.States, "select");
@Html.ValidationMessageFor(m => m.StateId);
<a class="edit" href="#">Edit</a>
<input type="submit" name="Submit" value="Submit" />
}
</body>
</html>
public class MyPractiseAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "MyPractise";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"MyPractise_default1",
"MyPractise/{controller}/{action}/{Val}",
new { action = "Index", Val = UrlParameter.Optional }
);
context.MapRoute(
"MyPractise_default",
"MyPractise/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}