我想从JSON类型数据中解析值并将其显示在文本框中。我设法将控制器中的json数据传递给查看。但我无法在查看的文本框中显示它。我试图使用 alert 显示值,但它只显示 [object] [Object]
查看
<div class="form-group">
@Html.LabelFor( model => model.StudentRegNo, htmlAttributes: new { @class = "control-label col-md-2" } )
<div class="col-md-10">
@Html.DropDownListFor( model => model.StudentRegNo, new SelectList( ViewBag.StudentListForDDL, "Value", "Text" ), "--SELECT--", new { @class = "form-control", @id = "studentReg" } )
@Html.ValidationMessageFor( model => model.StudentRegNo, "", new { @class = "text-danger" } )
</div>
</div>
<div class="form-group">
@Html.LabelFor( model => model.StudentName, htmlAttributes: new { @class = "control-label col-md-2" } )
<div class="col-md-10">
@Html.TextBoxFor( model => model.StudentName, new { @class = "form-control", @id = "StudentName" } )
</div>
</div>
@section Scripts {
<script src="~/Scripts/jquery-2.2.0.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
@*@Scripts.Render( "~/bundles/jqueryval" )*@
<script>
$(document).ready(function () {
$("#studentReg").change(function () {
var reg = $("#studentReg").val();
var json = { studentReg: reg };
$.ajax({
type: "POST",
url: '@Url.Action( "GetStudentByRegNo","Result")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function (data) {
//$.each(data, function (key, value) {
// //var name = value.StudentName;
// alert(key.StudentName);
//});
alert(data);
}
});
});
});
</script>}
控制器
public class ResultController : Controller {
private ResultManager objResultManager = new ResultManager();
// GET: Result
public ActionResult ViewResult() {
var studentList = objResultManager.GetListOfStudents();
List<SelectListItem> studetListItems = new List<SelectListItem>();
foreach (Student objStudent in studentList) {
studetListItems.Add(new SelectListItem {Value = objStudent.StudentRegNo, Text = objStudent.StudentRegNo});
}
ViewBag.StudentListForDDL = studetListItems;
return View();
}
//GET Student By Registration Number
public JsonResult GetStudentByRegNo(string studentReg) {
Student objStudent = objResultManager.GetStudentByRegNo(studentReg);
return Json(objStudent,JsonRequestBehavior.AllowGet);
}
}
模型
public class Student {
public string StudentRegNo { get; set; }
public string StudentName { get; set; }
public string StudentEmail { get; set; }
public string StudentContactNo { get; set; }
public DateTime StudentRegDate { get; set; }
public string StudentAddress { get; set; }
public string Department { get; set; }
}
我在这里做错了什么?
提前致谢。
答案 0 :(得分:1)
如果一切正常,请在控制器中使用以下
public JsonResult GetStudentByRegNo(string studentReg) {
Student objStudent = objResultManager.GetStudentByRegNo(studentReg).FirstOrDefult();
return Json(objStudent,JsonRequestBehavior.AllowGet);
}
然后在View中获取值
data.YourStudenPropertyName