[英]How to get value from JSON and show it in a textbox?
我想从JSON类型数据中解析值并将其显示在文本框中。 我设法将JSON数据从Controller传递到View 。 但是我只是不能在View的文本框中显示它。 我试图使用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; }
}
我在这里做错了什么?
提前致谢。
如果一切正常,请在控制器中使用以下内容
public JsonResult GetStudentByRegNo(string studentReg) {
Student objStudent = objResultManager.GetStudentByRegNo(studentReg).FirstOrDefult();
return Json(objStudent,JsonRequestBehavior.AllowGet);
}
然后在“查看”中获取价值
data.YourStudenPropertyName
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.