I’m learning ASP.NET MVC 2 and ran into a slight issue which I can’t seem to figure out.
Basically I have a drop down which is populated from an Access db and when the user selects a value I would like to call an ActionResult passing through the selected value as a parameter, I’m trying to achieve this by using $.post
The drop down is getting populated with data and I can confirm that the javascript function fires but the break point in my ActionResult is still not being hit, I’d appreciate any advice:
Model:
public class SuppliersModel
{
public SuppliersModel()
{
}
public SuppliersModel(string id)
{
}
private string id;
public string ID
{
get { return id; }
set { id = value; }
}
public SelectList OurSuppliers
{
get
{
List<SelectListItem> suppliers = GetSuppliers();
var list = new SelectList(suppliers, "Value", "Text");
return list;
}
}
public IEnumerable<string> UniqueSuppliers{get;set;}
private List<SelectListItem> GetSuppliers()
{
var suppliers = new List<SelectListItem>();
string conn = WebConfigurationManager.ConnectionStrings["connection"].ConnectionString;
using (var connection = new OleDbConnection(conn))
{
connection.Open();
string commandText = "SELECT [Supplier], [ID] FROM [Suppliers] ORDER BY [Supplier]";
using (var command = new OleDbCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string id = reader["ID"].ToString();
string supplier = reader["Supplier"].ToString();
suppliers.Add(new SelectListItem() { Text = supplier, Value = id });
}
}
}
connection.Close();
return suppliers;
}
}
}
Controller:
public class SuppliersController : Controller
{
public ActionResult Suppliers()
{
SuppliersModel model = new SuppliersModel();
return View(model);
}
[HttpPost]
public ActionResult SuppliersById(string id)
{
System.Diagnostics.Debugger.Break();
SuppliersModel model = new SuppliersModel(id);
return View(model);
}
}
View:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(function () {
$('#suppliers').change(function () {
debugger;
$.post('@Url.Action("SuppliersById", "Suppliers")', { id: $(this).val() },
function (result) {
});
});
});
</script>
<h2>
Suppliers</h2>
<div>
<%= Html.DropDownList("suppliers",Model.OurSuppliers) %>
</div>
<% if (Model.ID != null)
{ %>
<table>
<tr>
<th>
<h2>
List of suppliers
</h2>
</th>
</tr>
<% foreach (var item in Model.UniqueSuppliers)
{ %>
<tr>
<td>
<%: Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) %>
|
<%: Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ })%>
|
<%: Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })%>
</td>
</tr>
<% } %>
</table>
<% } %>
</asp:Content>
There was a syntax error in my javascript function, this fixed it: