Viewbag值未显示在ASP.NET MVC视图中



我正在使用C#和ASP.NET MVC,并尝试将数据从控制器传递到视图。当我调试时,数据显示在视图包中,但不显示在视图中。错误为未定义。我不知道为什么这个代码显示错误。

这是屏幕截图:

调试结果屏幕截图

C#代码:

public JsonResult mselectCOACodes(string gl_code)
{
ViewBag.mainCode = gl_code.Substring(0, 2) + "-00-00-0000";
if (ViewBag.mainCode != "")
{
ViewBag.mainDesc = _ICOA.mSelectChartofAccount(ViewBag.mainCode);
}
return Json("", JsonRequestBehavior.AllowGet);
}

jQuery:

<script type="text/javascript">
jQuery(document).ready(function ($) {
$("#txtvglcode").change(function () {
$.ajax({
type: "GET",
url: "/ChartofAccount/mselectCOACodes",
data: {
gl_code: $("#txtvglcode").val() 
},
contentType: "application/json; charset=utf-8",
dataType: "json",

failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>

查看

<div class="col-sm-6">
<div class="col-sm-3">
<div class="form-group">
<b>Main Code</b>
<div class="form-line">
<input type="text" id="txtglmainCode" 
value="@ViewBag.mainCode" class="form-control" placeholder="" />
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<b>Description</b>
<div class="form-line">
<input type="text" id="txtmainDescription" 
value="@ViewBag.mainDesc" class="form-control" placeholder="" />
</div>
</div>
</div>
</div>

首先,不要使用@ViewBag来存储输入值,因为您无法在C#代码中访问其值
这里是C#代码:

public JsonResult mselectCOACodes(string gl_code)
{
string mainCode = gl_code.Substring(0, 2) + "-00-00-0000";
if (mainCode != "")
{
string mainDesc = _ICOA.mSelectChartofAccount(ViewBag.mainCode);
}
return Json(mainDesc, JsonRequestBehavior.AllowGet);
}

这是JQuery:

<script type="text/javascript">
jQuery(document).ready(function ($) {
$("#txtvglcode").change(function () {
$.ajax({
type: "GET",
url: "/ChartofAccount/mselectCOACodes",
data: {
gl_code: $("#txtvglcode").val() 
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (mainDesc) {
$("#txtmainDescription").val(mainDesc);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>  

视图:

<div class="col-sm-6">
<div class="col-sm-3">
<div class="form-group">
<b>Main Code</b>
<div class="form-line">
<input type="text" id="txtglmainCode" 
value="" class="form-control" placeholder="" />
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<b>Description</b>
<div class="form-line">
<input type="text" id="txtmainDescription" 
value="" class="form-control" placeholder="" />
</div>
</div>
</div>
</div> 

最新更新