mee*_*na 5 c# asp.net asp.net-mvc jquery
我正在尝试根据另一个文本框填充文本框值,但我无法填充其他文本框.我正在分享我的代码,请指导我最好的解决方案
行动方法:
public JsonResult AgreementNo(string id)
{
string no;
string _str = id;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
SqlCommand cmd = new SqlCommand("SELECT top(1) num from loan where id=@str", con);
cmd.Parameters.AddWithValue("@str",id);
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
no = ds.Tables[0].Rows[0]["num"].ToString();
return Json(new
{
no = no
}, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
脚本:
$("#BarrowerName").blur(function () {
$.ajax({
url: '@Url.Action("AgreementNo", "Home")',
// url: '@Url.Action("AgreementNo", "Home")',
dataType: "json",
data: JSON.stringify({ id: $("#BarrowerName").val() }),
type:"POST",
async: false,
contentType: 'application/json,charset=utf-8',
sucess: function (data) {
$("#AgreementNo").val(data.no)
response(data);
}
});
});
Run Code Online (Sandbox Code Playgroud)
它抛出错误如下:将nvarchar值''转换为数据类型int时转换失败.
首先,您的错误在这一行:-
cmd.Parameters.AddWithValue("@str",id);
Run Code Online (Sandbox Code Playgroud)
由于您尝试将整数值传递给NVARCHAR列,因此请更改您的代码,如下所示:-
cmd.Parameters.Parameters.Add("@str",SqlDbType.NVarChar).Value = id;
Run Code Online (Sandbox Code Playgroud)
请阅读以下内容:-我们可以停止使用 AddWithValue
现在,一旦这个问题被修复,将你的 jQuery 代码从 改为sucess,success它应该可以工作了!
除此之外,使用using语句自动处置您的宝贵资源,如下所示:-
string CS = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
using(SqlCommand cmd = new SqlCommand("SELECT top(1) num from loan where id=@str", con))
{
cmd.Parameters.Parameters.Add("@str",SqlDbType.NVarChar).Value = id;
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
no = ds.Tables[0].Rows[0]["num"].ToString();
return Json(new
{
no = no
}, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1185 次 |
| 最近记录: |