I have list in model and the item from database. I want put the item to array in java script. then when I put values in textbox and click the button the system check from the array the values have in array or not
when I try this code, its not work. Any ideas or suggestion?
Model:
public List<string> listponumber { get; set; }
public void getlist()
{
var listpo = new List<string>();
SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
connection.Open();
SqlCommand cmdponumber = new SqlCommand("Select DISTINCT ponumber From t_transaction ORDER BY ponumber", connection);
SqlDataReader rdr = cmdponumber.ExecuteReader();
while (rdr.Read())
{
listpo.Add(rdr.GetString(0).ToString());
}
connection.Close();
listponumber = new List<string>(listpo);
}
View:
<script type="text/javascript">
$(document).ready(function () {
$("#btntest").click(function () {
var ponumber = [@Model.listponumber]
var txtvalues = document.getElementByID("textbox").value;
if (ponumber.indexOf(txtvalues) > -1 ) {
alert('Array');
} else {
alert('not array');
}
});
</script>
You can convert the C# List into a Javascript array by using
<script>
var javascriptArray = @Html.Raw(Json.Encode(Model.ListToConvertToJavascript));
</script>
This will create a Json object with the data inside the List in your Model and you will be able to iterate through it in plain Javascript.
The syntax error might you get is the IDE telling you that you are using a syntax that the Javascript parser doesn't understand, which is the RAZR sentece @Html(...); you can ignore it.
Test it out using:
for(int i = 0; i < $(javascriptArray).lenght; i++){
alert(javascriptArray[i]);
}
or opening your browser developer's console and typing the name of the array you are creating to see if it is populated by your Model List data.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments