Here I have two dropdownlists. First one to display the list of countries and the second to list the states value for selected country from first. The list of values are populated from
properly but in the dropdownlist, the values are not populated.
jQuery:
$(document).ready(function () {
$("#Country").change(function () {
var Id = $('#Country option:selected').attr('value');
$("#Region").empty();
$.getJSON("/ControllerName/GetRegionList",{ ID: Id },
function (data) {
jQuery.each(data, function (key) {
$("#Region").append($("<option></option>").val(ID).html(Name));
});
});
});
});
View :
#Html.DropDownList("Country", new SelectList(Model.CountryList, "Value", "Text", Model.CountryList.SelectedValue))
#Html.DropDownList("Region", new SelectList(Model.RegionList, "Value", "Text", Model.RegionList.SelectedValue))
Controller:
public List<Region> GetRegionList(int ID)
{
int countryid = ID;
AddressModel objmodel = new AddressModel();
List<Region> objRegionList = new List<Region>();
objRegionList.Add(new Region { ID = "0", Name = " " });
if (countryid != 0)
{
countryid = Convert.ToInt32(ID);
SqlCommand cmd = new SqlCommand("USP_ProcedureName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Id", countryid);
cmd.Parameters.AddWithValue("#Mode", "Region");
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr["RegionId"].ToString() != "")
{
objRegionList.Add(new Region { ID = dr["RegionId"].ToString(), Name = dr["Name"].ToString() });
}
}
dr.Close();
con.Close();
}
return objRegionList;
}
What is the mistake in my code.? Any Suggestions.
EDIT : Added the snapshot
In ASP.NET MVC controller actions must return ActionResults. In your case you could return JSON:
public ActionResult GetRegionList(int id)
{
var objRegionList = new List<Region>();
objRegionList.Add(new Region { ID = "0", Name = " " });
if (countryid != 0)
{
int countryid = ID;
using (var conn = new SqlConnection("YOUR CONNECTION STRING COMES HERE"))
using (var cmd = conn.CreateCommand())
{
con.Open();
cmd.CommandText = "USP_ProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Id", countryid);
cmd.Parameters.AddWithValue("#Mode", "Region");
using (var dr = cmd.ExecuteReader())
{
while (dr.Read())
{
if (dr["RegionId"].ToString() != "")
{
objRegionList.Add(new Region
{
ID = dr["RegionId"].ToString(),
Name = dr["Name"].ToString()
});
}
}
}
}
}
return Json(objRegionList, JsonRequestBehavior.AllowGet);
}
Notice that I have also cleared your code from unused variables and unnecessary Convert.ToInt32 calls and most importantly wrapped IDisaposable resources such as SQL connections, commands and data readers in using statements to avoid leaking resources.
Then include the url of the controller action as a data-* attribute on the first dropdown to avoid ugly hardcoding it in your javascript and breaking when you deploy your application in IIS in a virtual directory:
#Html.DropDownList(
"Country",
new SelectList(Model.CountryList, "Value", "Text", Model.CountryList.SelectedValue),
new { data_url = Url.Action("GetRegionList", "ControllerName") }
)
finally adapt (simplify) your javascript:
$('#Country').change(function () {
var regionDdl = $('#Region');
regionDdl.empty();
var id = $(this).val();
var url = $(this).data(url);
$.getJSON(url, { id: id }, function (data) {
$.each(data, function (index, region) {
regionDdl.append(
$('<option/>', {
value: region.ID,
html: region.Name
})
);
});
});
});
Related
I have a wcf service used to populate cascading drop down list in a ASPX page in IIS 7. The drop down list gets thousands of empty option tags but no data. The service does not throw an error. The entire solution runs in IDE on desktop but the service is not working correctly when deployed on IIS. I suspect it is an IIS issue but can not identify it.
<snippet from aspx page>
<asp:DropDownList ID="ddCommercialServicesSiteName" runat="server" Width="150"></asp:DropDownList>
<ajaxToolkit:CascadingDropDown
ID="cddCommercialServicesSiteName" TargetControlID="ddCommercialServicesSiteName"
PromptText="Select" PromptValue="" Category="siteID"
ServicePath="~/ServiceDropDown.svc" ServiceMethod="GetCommercialSites"
LoadingText ="Loading..." runat="server"/>
<!-- ServiceDropDown.svc code -->
<%# ServiceHost Language="C#" Debug="true" Service="ReportDashboard.ServiceDropDown" CodeBehind="ServiceDropDown.svc.cs" %>
public List GetCommercialSites(string knownCategoryValues, string contextKey)
{
List sites = new List();
if (contextKey == null)
{
return sites;
}
string query = #"select DISTINCT ContactName AS Site , id from sites";
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
cmd.Connection = con;
cmd.Parameters.Add("#account", SqlDbType.VarChar).Value = contextKey.ToString();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
sites.Add(new CascadingDropDownNameValue
{
name = reader[0].ToString(),
value = reader[1].ToString(),
});
}
reader.Close();
con.Close();
}
}
return sites;
}
Try this approach to retrieve values from the Reader.
List<MyModelClass> result = new List<MyModelClass>();
while (reader.Read())
{
object[] values = new object[3];
reader.GetValues(values);
MyModelClass model = new MyModelClass();
model.ID = values[0].ToString();
model.ValueProperty = values[1].ToString();
model.ValueProperty2 = values[2].ToString();
result.Add(model);
}
In your View/aspx run a jQuery to populate your dropdown,
$("#dropdown").change(function () {
dropdown.append($("<option></option>").val("").html("Please wait ..."));
$.ajax({
url: "/api/CascadingData/GetSomeData/",
type: "GET",
dataType: "json",
data: { Id: Id },
success: function (d) {
dropdown.empty(); // Clear the list, including the please wait option
dropdown.append($("<option></option>").val('').html("Select an option..."));
$.each(d, function (i, ModelObject) {
dropdown.append($("<option></option>").val(ModelObject.Name).html(ModelObject.Value));
});
},
error: function () {
alert("Error in $('#dropdown').change!");
}
});
}
I am trying to save array of data in database how to achieve it.
I have a form where three inputs PRODUCT_ID, TDC_NO, REVISION are there along with array list of values generated dynamically (sizeMin, sizeMax, tolMin, tolMax). I want to store those dynamically generated values in Prop_detail whose structure I have mentioned at below and PRODUCT_ID, TDC_NO, REVISION values in tdcProduct1 table whose structure I designed below.how to pass those array list of values from server side to database .and how to store further in database.
.aspx
<script type="text/javascript">
$(document).on("click", "[id*=btnFrmSubmit]", function () {
var user = {};
user.PRODUCT_ID = 1;
user.TDC_NO = $("[id*=Tdc_No]").val();
user.REVISION = $("#Revision").text();
/* Creating Array object as WireDimDetails to add in user object*/
var WireDimDetails = new Array();
$("#WireDimTbl tbody tr").each(function () {
var row = $(this);
/* Declare and sets the WireDimDetail object with the property which will add in WireDimDetails array object*/
var WireDimDetail = {};
var sizeMin = row.find("[id^=SizeMin]").val();
/* Checking if control exist or not else assign empty value in sizeMax*/
var sizeMax = row.find("[id^=SizeMax]") != "undefined" ? row.find("[id^=SizeMax]").val() : "";
var tolMin = row.find("[id^=TolMin]").val();
var tolMax = row.find("[id^=TolMax]").val();
/*Sets the Values of controls */
WireDimDetail.SizeMin = sizeMin;
WireDimDetail.SizeMax = sizeMax;
WireDimDetail.TolMin = tolMin;
WireDimDetail.TolMax = tolMax;
/*Add WireDimDetail object in WireDimDetails Array object*/
WireDimDetails.push(WireDimDetail);
})
/*Add WireDimDetails array of object to user object*/
user.WireDimDetails = WireDimDetails;
$.ajax({
type: "POST",
url: "TDC.aspx/SaveFrmDetails",
data: JSON.stringify({ user: user, }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Data has been added successfully.");
window.location.reload();
},
error: function (response) { alert(response.responseText); }
});
</script>
Server side
[WebMethod]
public static void SaveFrmDetails(User user)
{
string connectionString = ConfigurationManager.ConnectionStrings["conndbprodnew"].ConnectionString;
using (OracleConnection con = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand("INSERT INTO TDC_PRODUCT1(PRODUCT_ID,TDC_NO, REVISION) VALUES (:PRODUCT_ID,:TDC_NO,:REVISION )",con))
{
cmd.CommandType = CommandType.Text;
List<WireDimDetail> wireDimDetails = user.WireDimDetails;
for (int i = 0; i < wireDimDetails.Count; i++)
{
WireDimDetail wireDimDetail = wireDimDetails[i];
string sizeMin = wireDimDetail.SizeMin;
string sizeMax = !string.IsNullOrEmpty(wireDimDetail.SizeMax) ? wireDimDetail.SizeMax : "0"; // set default value
string tolMin = wireDimDetail.TolMin;
string tolMax = wireDimDetail.TolMax;
}
cmd.Parameters.AddWithValue(":PRODUCT_ID",user.PRODUCT_ID);
cmd.Parameters.AddWithValue(":TDC_NO", user.TDC_NO);
cmd.Parameters.AddWithValue(":REVISION", user.REVISION);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Table structure for saving data and array list of data, tdcProduct1 table consist of three columns:
Productid | Tdc_no | Revision
And second table Prop_detail:
Tdc_no | Tdc_property
My concern is how to store an array of data in Prop_detail table at the same time while storing data in tdcProduct1 using SaveFrmDetails. Any ideas would be appreciated.
I think you want to save multiple WireDimDetail to Prop_detail per user
so a simple way is loop through the wireDimDetails and get string of wireDimDetail for inserting in Tdc_property.
After inserting row in TDC_PRODUCT1, for inserting details the code would be like:
[WebMethod]
public static void SaveFrmDetails(User user)
{
string connectionString = ConfigurationManager.ConnectionStrings["conndbprodnew"].ConnectionString;
using (OracleConnection con = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand("INSERT INTO TDC_PRODUCT1(PRODUCT_ID,TDC_NO, REVISION) VALUES (:PRODUCT_ID,:TDC_NO,:REVISION )", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue(":PRODUCT_ID", user.PRODUCT_ID);
cmd.Parameters.AddWithValue(":TDC_NO", user.TDC_NO);
cmd.Parameters.AddWithValue(":REVISION", user.REVISION);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "insert into Prop_detail(Tdc_no,Tdc_property) values(#tdN,#tdProp)";
foreach (WireDimDetail wireDimDetail in user.WireDimDetails)
{
cmd.Parameters.Clear();
var stringwriter = new System.IO.StringWriter();
var serializer = new System.Xml.Serialization.XmlSerializer(wireDimDetail.GetType());
serializer.Serialize(stringwriter, wireDimDetail);
cmd.Parameters.AddWithValue("#tdN", user.TDC_NO);
cmd.Parameters.AddWithValue("#tdProp", stringwriter.ToString());
cmd.ExecuteNonQuery();
}
con.Close();
}
}
}
the stringwriter is string of each WireDimDetail.
but if you want to new record for sizeMin,sizeMax,tolMin and tolMax change foreach loop to:
foreach (WireDimDetail wireDimDetail in user.WireDimDetails)
{
cmd.Parameters.Clear();
string[] strNumbers = new string[4]
{
wireDimDetail.SizeMin,
!string.IsNullOrEmpty(wireDimDetail.SizeMax) ? wireDimDetail.SizeMax : "0",
wireDimDetail.TolMin,
wireDimDetail.TolMax
};
foreach (string number in strNumbers)
{
cmd.Parameters.AddWithValue("#tdN", user.TDC_NO);
cmd.Parameters.AddWithValue("#tdProp", number);
cmd.ExecuteNonQuery();
}
}
EDIT:
The final try would be like :
[WebMethod]
public static void SaveFrmDetails(User user)
{
string connectionString = ConfigurationManager.ConnectionStrings["conndbprodnew"].ConnectionString;
using (OracleConnection con = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand("INSERT INTO TDC_PRODUCT1(PRODUCT_ID,TDC_NO, REVISION) VALUES (:PRODUCT_ID,:TDC_NO,:REVISION )", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue(":PRODUCT_ID", user.PRODUCT_ID);
cmd.Parameters.AddWithValue(":TDC_NO", user.TDC_NO);
cmd.Parameters.AddWithValue(":REVISION", user.REVISION);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "insert into Prop_detail(Tdc_no,Rowno,Prop_Name,Tdc_property) values(#tdN,#rowNo,#propN,#tdProp)";
int rowNum = 1;// You can get rowNum from DB and initiate it to last rowNum
foreach (WireDimDetail wireDimDetail in user.WireDimDetails)
{
cmd.Parameters.Clear();
Dictionary<string, string> strNumbers = new Dictionary<string, int>()
{
{"sizMin", wireDimDetail.SizeMin },
{"sizeMax" , !string.IsNullOrEmpty(wireDimDetail.SizeMax) ? wireDimDetail.SizeMax.ToString() : "0" },
{"tolMin", wireDimDetail.TolMin.ToString() },
{"tolMax", wireDimDetail.TolMax.ToString() }
};
cmd.Parameters.Clear();
foreach (KeyValuePair<string, string> kvp in strNumbers)
{
cmd.Parameters.AddWithValue("#tdN", user.TDC_NO);
cmd.Parameters.AddWithValue("#rowNo", rowNum);
cmd.Parameters.AddWithValue("#propN", kvp.Key);
cmd.Parameters.AddWithValue("#tdProp", kvp.Value);
cmd.ExecuteNonQuery();
}
rowNum++;
}
con.Close();
}
}
}
NOTES:
1- rowNum can be retrieved from DB and then increase (can be initiated by select max(rowNo) from Prop_detail).
2- I used dictionary to hold the name of variable such as sizeMax and etc, there are many ways to do this
I have jqgrid implemented successfully, I have some questions regarding posting the data selected to controller
How can I maintain track of selected rows means how can I save the data in a list array?
How can I pass back to Data table to show the results again like no of rows selected and sum of row values selected etc. Please help. I am posting my jquery code as well as controller code. thanks in advance.
View:
onSelectRow: function (id, status)
{
alert('polo');
var rowData = jQuery(this).getRowData(id);
FirstName = rowData['FirstName'];
LastName = rowData['LastName'];
Salary = rowData['Salary'];
Gender = rowData['Gender'];
$.ajax({
url: '/TodoList/notCk_Pk',
data:{'FirstName':FirstName,'LastName':LastName,'Salary':Salary,'Gender':Gender},
type: "post"
})
$('#example').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "/TodoList/notCk_Pk",
"sAjaxDataProp": "",
"columns": [
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "Salary" },
{ "data": "Gender" },
]
});
}
Controller code:
public ActionResult notCk_Pk(String FirstName,String LastName,int Salary,String Gender)
{
l.Add(FirstName);
l1.Add(LastName);
i = Salary + i;
l2.Add(Gender);
string ConnectionString = ConfigurationManager.ConnectionStrings["EmployeeContext"].ConnectionString;
using (SqlConnection connection = new SqlConnection("data source=.; database=Srivatsava; integrated security=SSPI"))
{
connection.Open();
SqlCommand com = new SqlCommand("insertinto", connection);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FirstName", FirstName);
com.Parameters.AddWithValue("#LastName",LastName);
com.Parameters.AddWithValue("#Salary", Salary);
com.Parameters.AddWithValue("#Gender", Gender);
com.ExecuteNonQuery();
connection.Close();
}
var todoListsResults = l.Count();
var t1=l1.Count();
var t3=l2.Count();
var aaData=new{
todoListsResults,
t1,
i,
t3
};
return Json(aaData, JsonRequestBehavior.AllowGet);
//Console.WriteLine(FirstName + "" + LastName + "" + Salary + "" + Gender);
//return Content("<script language='javascript' type='text/javascript'>alert("+FirstName+");</script>");
}
each time when I select a row it is initalizing the i variable to '0' even though I made it global.
You don't need to use list array. You can get all selected row using $("#ListGrid").jqGrid('getGridParam', 'selarrrow'). Following code snippet may help you.
onSelectRow: function(id, status) {
var currentRow = $(this).getRowData(id);
FirstName = currentRow['FirstName'];
LastName = currentRow['LastName'];
Salary = currentRow['Salary'];
Gender = currentRow['Gender'];
$.ajax({
url: '/TodoList/notCk_Pk',
data:{'FirstName':FirstName,'LastName':LastName,'Salary':Salary,'Gender':Gender},
type: "post"
})
var rows = $("#ListGrid").jqGrid('getGridParam', 'selarrrow');
var totalRow = rows.length;
var totalAmount = 0;
$.each(rows, function() {
var rowData = $("#ListGrid").getRowData(this);
totalAmount += rowData["Salary"] * 1;
});
dataTable.row($('#example').find('tbody tr')).remove().draw();
dataTable.row.add([totalRow, totalAmount]).draw();
}
DEMO
I am new in JQuery and API, here i am trying to retrieve data from SQL in JSON format and then bind it to table. Data is returned here return details.ToString(); when I debug but it does not bind data into table. Any Error here?
Controller:
public class EmployeeController : ApiController
{
static EmpRepository repository = new EmpRepository();
public string GetData(Employee Em) {
var re = repository.GetData(Em);
return re;
}
}
Repository Class:
public string GetData(Employee Em)
{
DataTable dt = new DataTable();
List<Employee> details = new List<Employee>();
connection();
com = new SqlCommand("select FirstName, LastName, Company from Employee", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
Employee user = new Employee();
//user.Id = Int32.Parse(string dr["Id"]);
user.FirstName = dr["FirstName"].ToString();
user.LastName = dr["LastName"].ToString();
user.Company = dr["Company"].ToString();
details.Add(user);
}
return details.ToString();
}
JQuery:
$(document).ready(function DisplayResult() {
var Emp = {};
var url = 'api/Employee/GetData';
$.ajax({
type: "POST",
url: url,
contentType: "application/json;charset=utf-8",
//data: {},
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++)
{
$("#tbDetails").appendTo("<tr><td>" + data.d[i].FirstName + "</td><td>" + data.d[i].LastName + "</td><td>" + data.d[i].Company + "</td></tr>");
}
},
error: function (result) {
alert("error");
}
});
});
Here are the changes you need to do each section.
First in your Repository just return the details as is not details.ToString()
Next in both your repository class as well as in WebApi controller you don't need to Employee parameter you are not using it anywhere. Remove it.
Repository Class ->
public string GetData()
{
DataTable dt = new DataTable();
List<Employee> details = new List<Employee>();
connection();
com = new SqlCommand("select FirstName, LastName, Company from Employee", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
Employee user = new Employee();
// user.Id = Int32.Parse(string dr["Id"]);
user.FirstName = dr["FirstName"].ToString();
user.LastName = dr["LastName"].ToString();
user.Company = dr["Company"].ToString();
details.Add(user);
}
return details;
}
WebApi Controller :
You don't need to convert anything to JSON here, by default JSON.NET serializer will convert your List to JSON Array of Employee Objects.
public class EmployeeController : ApiController
{
static EmpRepository repository = new EmpRepository();
public string GetData() {
var re = repository.GetData();
return re;
}
}
Now in your jquery :
Ideally you are doing a 'GET' here not a POST , data returned now is an array of employee objects iterate through it.
$(document).ready(function DisplayResult() {
var Emp = {};
var url = 'api/Employee/GetData';
$.ajax({
type: "GET",
url: url,
contentType: "application/json;charset=utf-8",
success: function (data) {
for (var i = 0; i < data.length; i++)
{
$("#tbDetails").appendTo("<tr><td>" + data[i].FirstName + "</td><td>" + data[i].LastName + "</td><td>" + data[i].Company + "</td></tr>");
}
},
error: function (result) {
alert("error");
}
});
});
I think you have two mistakes in your code.
On "public string GetData(Employee Em) "
I think that you want to return list of Employee
so should change return details.ToString(); toreturn details;`
It will be
public List<Employee> GetData(Employee Em)
{
DataTable dt = new DataTable();
List<Employee> details = new List<Employee>();
connection();
com = new SqlCommand("select FirstName, LastName, Company from Employee", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
Employee user = new Employee();
// user.Id = Int32.Parse(string dr["Id"]);
user.FirstName = dr["FirstName"].ToString();
user.LastName = dr["LastName"].ToString();
user.Company = dr["Company"].ToString();
details.Add(user);
}
return details; }
-Change GetData api, must return JSON format. It will be as below
public string GetData(Employee Em) {
var re = repository.GetData(Em);
return Json(re);}
and
for (var i = 0; i < data.d.length; i++)
{
$("#tbDetails").appendTo("<tr><td>" + data.d[i].FirstName + "</td><td>" + data.d[i].LastName + "</td><td>" + data.d[i].Company + "</td></tr>");
}
change to
for (var i = 0; i < data.length; i++)
{
$("#tbDetails").appendTo("<tr><td>" + data[i].FirstName + "</td><td>" + data[i].LastName + "</td><td>" + data[i].Company + "</td></tr>");
}
Good luck!
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is a NullReferenceException in .NET?
I am a beginner in MVC and I have tried to add a dropdown list to save its selected value in database using sql queries but my code throws a NullReferenceException.
Can anyone help me please?
This is the model
public class caradvert
{
[Required]
public SelectList GearType { get; set; }
public int Selected { get; set; }
public caradvert()
{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem()
{
Value = "0",
Text = "اتوماتيك "
});
listItems.Add(new SelectListItem()
{
Value = "1",
Text = "عادي"
});
GearType = new SelectList(listItems, "Value", "Text");
}
public int CreatAdvert(int userid)
{
SqlConnection objConn = new SqlConnection("Data Source=ADMIN-PC;Initial Catalog=mvc4advertisment;Integrated Security=True");
SqlCommand objCmd = new SqlCommand();
objCmd.CommandType = CommandType.Text;
objCmd.CommandText = "insert into Mercedes(Model,GearType,color,EngineCapacity,CarDescription,Price,Image1Url,Image2Url,Image3Url,Userid,State) values('1','" + GearType.SelectedValue.ToString() + "','r','221','ddd','2','ss','ss','ss','1','False')";
objCmd.Connection = objConn;
objConn.Open();
int count = (int)objCmd.ExecuteNonQuery();
objConn.Close();
return count;
}
}
This is controller
[HttpGet]
public ActionResult CreateAdvert()
{
caradvert model = new caradvert();
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem()
{
Value = "1",
Text = "اتوماتيك "
});
listItems.Add(new SelectListItem()
{
Value = "1",
Text = "عادي"
});
model.GearType = new SelectList(listItems, "Value", "Text");
return View(model);
}
[HttpPost]
public ActionResult CreateAdvert(caradvert model )
{
int _records = model.CreatAdvert(1);
if (_records > 0)
{
return RedirectToAction("Index", "Account");
}
else
{
ModelState.AddModelError("", "لا يمكنك اضافة اعلان");
}
return View(model);
}
This is the view
<%:Html.DropDownListFor(m=>m.Selected,Model.GearType,") %>
Most likely the GearType or GearType.SelectedValue are null in this statement.
objCmd.CommandText = "insert into Mercedes(Model,GearType,color,EngineCapacity,CarDescription,Price,Image1Url,Image2Url,Image3Url,Userid,State) values('1','" + GearType.SelectedValue.ToString() + "','r','221','ddd','2','ss','ss','ss','1','False')";
at this line:
objCmd.CommandText = "insert into Mercedes(Model,GearType,color,EngineCapacity,CarDescription,Price,Image1Url,Image2Url,Image3Url,Userid,State) values('1','" + GearType.SelectedValue.ToString() + "','r','221','ddd','2','ss','ss','ss','1','False')";
If GearType is not initialized or null
If GearType.SelectedValue is null
GearType.SelectedValue.ToString() can throw an exception like reference not set to an instance of an object.
To make problem more clear you can control GearType and GearType.SelectedValue before this line.
if(GearType != null && GearType.SelectedValue != null) {
Mercedes(Model,GearType,color,EngineCapacity,CarDescription,Price,Image1Url,Image2Url,Image3Url,Userid,State) values('1','" + GearType.SelectedValue.ToString() + "','r','221','ddd','2','ss','ss','ss','1','False')";
}