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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With