Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate the textbox value based on another textbox from database

i'm trying to populate textbox value based on another textbox but i cannot populate the the other textbox. i'm sharing my code please guide me with best solution

Action Method:

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

Script:

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

It Throwing the error like:Conversion failed when converting the nvarchar value '' to data type int.

like image 215
meena Avatar asked Sep 30 '22 03:09

meena


1 Answers

First of all your error is in this line:-

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

Since you are trying to pass an integer value to NVARCHAR column, Please change your code like this:-

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

Please read this:- Can we stop using AddWithValue

Now, once this is fixed, change your jQuery code from sucess to success and it should work!

Apart from this, use using statement to automatically dispose your valuables resources something like this:-

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);
}
like image 171
Rahul Singh Avatar answered Oct 03 '22 03:10

Rahul Singh