Premise: I'm new with MVC, and my english is not perfect, I hope you'll understand my post, otherwise I'm here for explainations.
I'm working on a project created by another developer in ASP.Net MVC and I have this problem:
In a View I have two cascading DropDownList: one with the Distributors and the other with the Vendors of the Distributor selected in the first DropDownList.
This is the code:
In the Body:
<tr>
<td>
<span>Distributor</span>
</td>
<td>
@Html.DropDownList("DistributorID")
@Html.ValidationMessageFor(model => model.DistributorID)
</td>
</tr>
<tr>
<td>
<span>Vendor</span>
</td>
<td class="tdAlignLeft">
@Html.DropDownList("VendorCode")
@Html.ValidationMessageFor(model => model.ClientHeaderInformation.VendorCode)
</td>
</tr>
In the Script:
$("#DistributorID").change(function (e) {
var SelectGroupId =$(this).val();
$.getJSON('@Url.Action("VendorByDistributor", "ClientInfo")', { VendorGroup: DistributorID }, function (param) {
var vendorCodes = $('#VendorCode');
vendorCodes.empty();
$.each(param, function (index, param) {
vendorCodes.append(
$('<option/>')
.attr('value', param.vendorCode)
.text(param.vendorName)
);
});
});
});
In the Controller:
public ActionResult VendorByDistributor(int _DistributorID)
{
var Vendors = db.View_Vendors.Where(n => n.DistributorID.Equals(_DistributorID)).Select(
x => new
{
vendorCode = x.VendorCode,
vendorName = x.VendorName
});
return Json(Vendors, JsonRequestBehavior.AllowGet);
}
'View_Vendors' is a SQL Server view, mapped with Entity Framework, this is the SQL:
SELECT A.DistributorID, A.DistributorName, B.VendorName, B.VendorCode
FROM dbo.Distributors AS A LEFT OUTER JOIN dbo.Vendors AS B ON
A.VendorCode = dbo.Vendor.VendorCode
All seems to work well, but when I save the view sometimes the VendorCode property of the ClientInfo class hasn't the last selected value. This happens if I change The Distributor on the first DropDownList, in this case the second DropDownList (Vendors) gets the right values, but if I select a Vendor and then I save the model, the property VendorCode has still the first value.
I also tried to create a function to test the event 'change' of the Vendors DropDownList ...
$ ("# VendorCode.") Change (function (e) {
SelectId var = $ (this). val ();
$. getJSON ('@ Url.Action ("updateVendorCode", "ClientInfo")', {VendorCodePass: SelectId});
});
... and in fact the event fires correctly only if I not change the Distributor and the Vendor items are not reloaded, in that case the event fires only the first time.
Sounds like a refresh problem of the second DropDownList Vendors, but I can't find the solution ...
Pileggi