I am calling a ajax method for a number of hidden client ids on an aspx page. The ajax method returns some html to a div provided.
So the code looks like below:
<asp:HiddenField runat="server" ID="hdnSomeProperty" Value="False"/>
<asp:HiddenField runat="server" ID="hfMyIndex" Value="0" />
<asp:HiddenField runat="server" ID="hfCustId" />
<asp:HiddenField runat="server" ID="hfCarId" />
<asp:HiddenField runat="server" ID="hfVanId" />
<asp:HiddenField runat="server" ID="hfTruckId" />
<asp:HiddenField runat="server" ID="hfMotorCycleId" />
var carNode = "<%=VechileNodeTypeEnum.Car.ToString() %>";
var selectedCarIds = $('#<%=hfCarId.ClientID %>').val();
ajaxMethod('/MyPage/MyMethod', { custId: custId, vechileNodeType: carNode, selectedIds: selectedCarIds }, '#carDiv');
var vanNode = "<%=VechileNodeTypeEnum.Van.ToString() %>";
var selectedVanIds = $('#<%=hfVanId.ClientID %>').val();
ajaxMethod('/MyPage/MyMethod', { custId: custId, vechileNodeType: vanNode, selectedIds: selectedVanIds }, '#vanDiv');
var truckNode = "<%=VechileNodeTypeEnum.Truck.ToString() %>";
var selectedTruckIds = $('#<%=hfTruckId.ClientID %>').val();
ajaxMethod('/MyPage/MyMethod', { custId: custId, vechileNodeType: truckNode, selectedIds: selectedTruckIds }, '#truckDiv');
var motorcycleNode = "<%=VechileNodeTypeEnum.MotorCycle.ToString() %>";
var selectedMotorcycleIds = $('#<%=hfMotorCycleId.ClientID %>').val();
ajaxMethod('/MyPage/MyMethod', { custId: custId, vechileNodeType: motorcycleNode, selectedIds: selectedMotorcycleIds }, '#motorcycleDiv');
Everything works as expected however I dont like the pattern of repeating the code 4 times with just a few of the proerties changed - I was think I could perhaps use a for loop and loop round 4 times - not sure how I would pass the changed properties dynamically though?
1 Answer 1
You should create a function that would wrap the ajax call and use it as many times as you wish.
var callMyMethod = function(nodeType, clientId, target) {
var ids = $('#' + clientId).val();
ajaxMethod('/MyPage/MyMethod', {
custId: custId, // is it a global variable?
vehicleNodeType: nodeType,
selectedIds: ids
}, target);
};
callMyMethod('<%=VechileNodeTypeEnum.Car.ToString()%>', '<%=hfCarId.ClientID%>', '#carDiv');
callMyMethod('<%=VechileNodeTypeEnum.Van.ToString()%>', '<%=hfVanId.ClientID%>', '#vanDiv');
callMyMethod('<%=VechileNodeTypeEnum.Truck.ToString()%>', '<%=hfTruckId.ClientID%>', '#truckDiv');
callMyMethod('<%=VechileNodeTypeEnum.MotorCycle.ToString()%>', '<%=hfMotorCycleId.ClientID%>', '#motorCycleDiv');
If there is some correlation between for example hfCarId.ClientID
and #carId
, you can remove the target
argument from the function.
It should be also possible to generate these calls by iterating over Car
, Van
, Truck
and MotorCycle
but I'm not that familiar with .net to suggest it to you.