我想在我的控制器操作中傳遞學生 ID,我使用了 JsonResult 操作,我捕獲了學生 ID,但無法通過操作,
這是我的 JavaScript 代碼,
<script type="text/javascript">
$(document).ready(function () {
$("#sId").change(function(){
var studentId = $(this).val();
debugger
$.ajax({
type:"post",
url:"/Department/GetDeptName/" studentId,
contentType:"html",
success:function(response){
debugger
$("#dId").empty();
$("#did").append(response);
}
})
})
});
</script>
我有一個下拉串列,我使用 ViewBag 從資料庫傳遞我的串列。當我選擇一個學生姓名時,需要傳遞他/她的部門名稱。這是查看代碼
<div class="row">
<div class="col-md-6 mb-4">
<label asp-for="Name" class="control-label">Student Name</label>
<select asp-for="Id" class="form-control" id="sId"
asp-items="@(new SelectList(@ViewBag.messageStudent,"Id", "Name"))">
</select>
</div>
<div class="col-md-6 mb-4">
<label asp-for="DeptName" class="control-label">Department Name</label>
<input asp-for="DeptName" id="dId" class="form-control mb-3" type="text" placeholder="Dept Name" disabled>
</div>
<input type="hidden" asp-for="Id" name="Id" id="DeptName" />
</div>
這是我的控制器代碼,將串列從資料庫傳遞到視圖
public async Task<IActionResult> DropDown()
{
var model = _scope.Resolve<FormModel>();
await model.LoadStudenDataAsync();
var studentList = model.StudentList.ToList();
studentList.Insert(0, new Student { Id = 0, Name = "Select Group" });
ViewBag.messageStudent = studentList;
return View(model);
}
現在我需要從查看頁面傳遞學生 id,如果我傳遞學生 id,那么我解決了我的問題,這是我的 JsonResult 操作
public async Task<JsonResult> GetDeptName(int studentId)
{
var model = _scope.Resolve<FormModel>();
if (ModelState.IsValid)
{
await model.DeptList(studentId);
}
return Json(model);
}
請幫助我任何人如何通過學生證,在此先感謝
uj5u.com熱心網友回復:
您必須使用 get ajax,因為您沒有在請求正文中發布任何資料。并將資料型別更改為 json,因為您要回傳 json
$.ajax({
type:"GET",
url:"/Department/GetDeptName/" studentId,
dataType: 'json',
....
和行動
[Route("~/Department/GetDeptName/{studentId}")]
public async Task<JsonResult> GetDeptName(int studentId)
并修復路由配置
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
但是如果您使用不支持屬性路由的舊網路,那么只需更改 ajax 并保持現在的操作
$.ajax({
type:"GET",
url:"/Department/GetDeptName?studentId=" studentId,
dataType: 'json',
....
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/442435.html
標籤:javascript jQuery asp.net-mvc 模型视图控制器 c#-4.0
