c# - 根据数据库中的另一个文本框填充文本框值

标签 c# jquery asp.net asp.net-mvc

我正在尝试根据另一个文本框填充文本框值,但我无法填充另一个文本框。我正在分享我的代码,请指导我提供最佳解决方案

操作方法:

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);
    }

脚本:

 $("#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);
}
});                           
});

它抛出如下错误:将 nvarchar 值 '' 转换为数据类型 int 时转换失败。

最佳答案

首先你的错误是在这一行:-

cmd.Parameters.AddWithValue("@str",id);

由于您正试图将整数值传递给 NVARCHAR 列,请像这样更改您的代码:-

cmd.Parameters.Parameters.Add("@str",SqlDbType.NVarChar).Value = id;

请阅读:- Can we stop using 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);
}

关于c# - 根据数据库中的另一个文本框填充文本框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27644523/

相关文章:

c# - ASP :CheckBoxList with parents

javascript - 为什么不能从 javascript 更改 asp.net 中的标签文本?

jquery - 在 css 中覆盖系统样式外观在 asp.net 中不起作用

javascript - 检查单选按钮是否被选中

javascript - 文档级事件监听器被复制

c# - C#代码同一行上的ASPX网站错误

c# - 将 wsdl Fedex 文件添加到 c# .Net

c# - 将代码从kinect sdk beta转换为最新的kinect sdk的完整指南

c# - c#中sql查询列中的无限小数值

c# - 存储库和服务层交互问题