ASP.NET MVC - Adding form elements at runtime with javascript - javascript

In my form I'm adding a number of input elements in a For Loop, as below.
#For Each itm As LineItem In Model.LineItems
Dim lnitm As LineItem = itm
#<tr>
<td>#lnitm.Name
</td>
<td>#Html.TextBoxFor(Function(model) model.LineItem(lnitm.ID).Value)
</td>
<td>#Html.TextBoxFor(Function(model) model.LineItem(lnitm.ID).Currency)
</td>
</tr>
Next
I'd like to add some jQuery to the Currency textbox so I can get the autocomplete working.
In my other pages I've used a jQuery function such as:
$(function () {
$("#HomeCurrencyID").autocomplete({
source: function (request, response) {
$.ajax({
url: "/autocomplete/Currencies", type: "POST", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.ID + " (" + item.Symbol + ") " + item.Description, value: item.ID , id: item.ID }
}))
}
})
},
});
});
This works fine where I know the ID of the Input Element / where I'm specifically adding the element into the HTML and not adding it via a loop.
How can I add the jQuery functionality above to all currency textbox's created in the For Loop? Do I need to add Javascript at run time?
Resolution
Changed the Function declaration to a classname and added the class to the textbox as below;
$("#CurrencyClass")
#Html.TextBoxFor(Function(model) model.LineItem(lnitm.ID).Currency, New With {Key .class = "CurrencyClass"})
Thanks for the prompt response!

You'll need to be able to select all of these textboxes to run the auto-complete script against, to do this you can add a class, then update the selector in your script.
In the view: Give all of the textboxes a class using new {#class = "yourClass"} (or its VB equivalent) as the htmlAttributes parameter to the textbox helper (see http://msdn.microsoft.com/en-us/library/ee703535.aspx#Y200).
In the script: Replace $("#HomeCurrencyID") with $(".yourClass"), it will run those functions to all of the matched elements, which will be the textboxes with yourClass.

Related

Using iterative variable from C# for loop in JavaScript function

On one of my pages I have a for loop to iterate through a list of "Projects" (which is the main model for my website) and display some of their data. The following code is nested in a table and the middle cells removed for redundancy.
foreach (var item in Model.Projects)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.SubmissionNumber)</td>
<td>#Html.DisplayFor(modelItem => item.Status)</td>
<!-- and so on -->
<td>#Html.ActionLink("Detail", "DisplayDetails", new { id = item.ProjectID })</td>
</tr>
}
The "Detail" link in the last cell will ideally make a box pop up (I'm thinking of using a Modal via Bootstrap) containing all of the data for the project. The "DisplayDetails" controller action returns a partial view that presents this information, but since I'm not using JavaScript or anything to render the partial view on the current page it renders it as it's own unformatted page. This is the controller action:
[HttpGet]
public ActionResult DisplayDetails(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Project project = db.Projects.Find(id);
if (project == null)
{
return HttpNotFound();
}
return PartialView("~/Views/Projects/_Detail.cshtml", project);
}
Ideally I would pass the ID to the controller using AJAX like I did below (which is code from another page of my website, again edited to remove redudancy):
$("#show").on("click", function () {
$.ajax({
url: '/Projects/SearchTable',
type: "GET",
data: {
Line1: $('#' + '#Html.IdFor(m => m.Project.ProjectAddress.Line1)').val(),
// and so on
County: $('#' + '#Html.IdFor(m => m.Project.ProjectAddress.County)').val(),
}
}).done(function(partialViewResult) {
$(".wrapper").html(partialViewResult);
$(".wrapper").css('display', 'block');
});
});
And by doing this I can embed the partial view onto the current page instead of it opening as a new page. I'm just not sure how to pass the project ID for a specific row in the table as data to the controller. Is this even possible? If not is there another way to achieve the same result?
You can replace your ActionLink with this:
<td>Details</td>
Then,
$(".details").on("click", function (e) {
e.preventDefault();
var projectId = $(this).data('id');
// Make the AJAX call here...
});

Set td value based on another td name from ajax

I have the following table structre:
<tr>
<td class="name">
Stock1
</td>
<td class="price">
</td>
</tr>
<tr>
<td class="name">
Stock2
</td>
<td class="price">
</td>
</tr>
Based on the names Stock1 and Stock2, I need to set the corresponding price in the next td. I am web scraping the price thru ajax and trying to set the value as follows:
For Stock1:
$(document).ready(function() {
$.ajax({
*everything else working fine*
success: function(data) {
if($('.name').html().indexOf("Stock1") != -1) {
$(this).closest('tr').find('.price').html(data);
}
}
});
});
In this scenario, this is not working, which I'm expecting to be the td tag with class name where value is Stock1. If I replace this with ".name", the code works only if there's one name td. When I have two td tags with the class name, it doesn't work.
I need to get this done as soon as the document loads, and not on some event like mouse click or hover.
this doesn't refers to td.name element nor table.
The :contains() Selector selects all elements that contain the specified text to target the td and then use can use DOM relationship to target immediate following sibling td using .next().
$('td.name:contains("Stock1")').next('.price').html(data);
or
$('td.name:contains("Stock1")').closest('tr').find('.price').html(data);
You can also use .filter()
var var1 = 'Stock1';
$('td.name').filter(function(){
return this.textContent.indexOf(var1) != -1;
}).closest('tr').find('.price').html(data);
As per comment, now you are returning an array. So need to iterate the data object and target the desired element.
var data = [{
name: "Stock1",
price: "$12"
}, {
name: "Stock2",
price: "$15"
}]
$.each(data, function(_, d){
$('td.name').filter(function() {
return this.textContent.indexOf(d.name) != -1;
}).closest('tr').find('.price').html(d.price);
})
DEMO
Use the below code in success method, assuming the data would be in the format mentioned below.
success:function(data)
// Assigning dummy values for assumption
var data = [{
stockName: "Stock1",
price: "$12"
}, {
stockName: "Stock2",
price: "$15"
}]
// Iterating throw all td which has name [class] elements
$(".name").each(function(i, obj) {
// Dummy Validation as per the mock data to repalce the data as per the stockName
if ($(this).closest('tr').find('.name').text().trim() === data[i].stockName){
$(this).closest('tr').find('.price').html(data[i].price);
}
})
});
FIDDLE
success: function(data) {
$('.name').each(function(index, element) {
if ($(element).html().indexOf("Stock1") != -1) {
$(element).closest('tr').find('.price').html(data);
}
}
}
The current implementation may not work correctly if you have multiple Stocks are present on your page. So i will suggest you to modify your server side code a bit to return back node name (like Stock1) as well as its price. So that your ajax success data will have 2 components; like data.name and data.price. first one will get used to target DOM td and later one will be used to set the price text as follows:
For Stock1:
$(document).ready(function(){
$.ajax({
url: "someBaseURL?name=Stock1"
success: function(data) {
var name = data.name; //grab the stock name
var price = data.price; //grab the stock price
//iterate over all the names and target the one associated
$('.name').each(function(){
if($.trim($(this).text()).indexOf(name) != -1)
$(this).closest('tr').find('.price').html(price);
});
}
});
});

Populate and display an html table based on the values from two dropdown menus

I have two cascading dropdown boxes controlled with JQuery and Ajax objects. The first determines the values in the second. Then, once a selection is made in the second, the values from the two dropdowns would be used to find a record in an SQL table and display the record in an html table.
So far the dropdowns work correctly but I'm having difficulty getting the record from the database and then displaying it on screen. I've done this before by getting the database values, sending them to the view in a Json object, and using an Ajax object to to create the table with Jquery. However, in this case I don't mind if the page reloads and would like to use a simpler method.
What is a simple method of sending two values from two dropdowns to the controller, using those values to find a record in an sql table, sending the values from the record back to the view to be displayed? Also, I don't want anything to be displayed until the second dropdown box has a selection made.
Here is what I have so far:
Controller methods:
List<Car> GetCars()
{
using (var service = new Service())
{
return service.GetCars().OrderBy(x => x.CarName).Select(x => new Car
{
CarId = x.CarId,
CarName = x.CarName
}).ToList();
}
}
List<Color> GetColors(int carId)
{
using (var service = new Services())
{
return service.GetColors(carId).OrderBy(x => x.ColorName).Select(x => new Color
{
ColorId = x.ColorId,
ColorName = x.ColorName
}).ToList();
}
}
[HttpPost]
public ActionResult CurrentSaus(int townCode, int fiscalYear)
{
var colors = GetColors(carId);
return Json(new SelectList(colors, "ColorId", "ColorName"));
}
Jquery methods:
$(document).ready(function () {
$("#Car_CarId").change(function () {
var carId = $(this).val();
var carName = $(":selected", this).text();
// put the car name into a hidden field to be sent to the controller
document.getElementById("Car_CarName").value = carName;
getColors(carId);
})
});
function getColors(carId) {
if (carCode == "") {
$("#Color_ColorId").empty().append('<option value="">-- select color --</option>');
}
else {
$.ajax({
url: "#Url.Action("Colors", "HotWheels")",
data: { colorId: clrId },
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred");
},
success: function (data) {
var colors = "";
var numberOfColors = data.length;
if (numberOfColors > 1) {
colors += '<option value="">-- select color --</option>';
}
else {
var colorId = data[0].Value;
var colorName = data[0].Text;
document.getElementById("Color_ColorName").value = colorName;
}
$.each(data, function (i, color) {
colors += '<option value="' + color.Value + '">' + color.Text + '</option>';
});
$("#Color_ColorId").empty().append(colors);
}
});
}
and some of the html:
#Html.HiddenFor(x => x.Car.CarName)
#Html.HiddenFor(x => x.Color.ColorName)
<table>
<tr>
<td> Select Car:</td>
<td style="text-align:left">
#Html.DropDownListFor(
x => x.Car.CarId,
new SelectList(Model.CarList, "CarId", "CarName"),
"-- select town --")
<br />
#Html.ValidationMessageFor(x => x.Car.CarId)
</td>
</tr>
<tr>
<td> Select Color:</td>
<td colspan="4">
#Html.DropDownListFor(
x => x.Color.ColorId,
new SelectList(Model.ColorList, "ColorId", "ColorName"),
"-- select color --")
<br />
#Html.ValidationMessageFor(x => x.Color.ColorId)
</td>
</tr>
</table>
}
The easiest method is to use an old fashion FORM element and POST the values of the two drop downs to an action in your controller. That action would expect a carId and a colorId and use them to retrieve a record from the DB and then pass the result to your 'view' where you would take care of render/display the result.
Of course using this method has some caveats:
The entire page will refresh after a user selects a value from the
second drop down.
You would have to POST the form using JavaScript
when the user picks the second option, or at least enable a button so
the form can be POSTed.
You would have to keep track of the carId and
colorId in your controller and view
Another option is to use AJAX to POST (send to the server) the carId and colorId where and action in a controller will take care of using those parameters to find a record in the DB and then return a JSON object with the result. The response will be handled by a 'success' handler where you will take care parsing the JSON object and add rows to a table.
So if you feel more comfortable working on the server side of the code pick the first option, however if you prefer to use AJAX and do this in the front end use the later.

dynamically generating checkbox list from json

I'm dynamically generating a list of checkboxes based on the contents of json data:
Format of tempfairway:
[{"FairWay":"A"},{"FairWay":"B"}, {"FairWay":"C"}, {"FairWay":"D"}]
var topics = tempfairway;
var topicContainer = $('ul#fairway_list');
$.each(topics, function (iteration, item) { topicContainer.append(
$(document.createElement("li")).append(
$(document.createElement("input")).attr({
id: 'topicFilter-' + item,
name: item,
value: item,
type: 'checkbox',
checked: true
})
//onclick
.click(function (event) {
var cbox = $(this)[0];
alert(cbox.value);
})
).append(
$(document.createElement('label')).attr({
'for': 'topicFilter' + '-' + item
}).text(item)
)
)
});
The checkboxes generate fine with the correct number but i'm getting [object Object] instead of the name of the fairway.
Any ideas on how to fix this?
Couple of more questions to add to this:
-What if i wanted to display ONLY unique values in tempfairway?
-.Click is set to get the value of that single checkbox, what if i want to iterate through all the checkboxes and get the value of all the ones that were selected in the case that the user unselected any of them?
In the line:
> $.each(topics, function (iteration, item) {
item is an object like {"FairWay":"A"}, so where you have:
> .text(item)
you probably want:
.text(item.FairWay)
and similarly for other uses of item. Or you could store the value in a variable and use that:
var fairwayName = item.FairWay;
...
.text(fairwayName);

jquery autocomplete in variable length list

Trying to figure out how to do this, using Sanderson begincollectionitems method, and would like to use autocomplete with a field in each row.
I think I see how to add a row with an autocomplete, just not sure the approach for existing rows rendered with guid.
Each row has an of field that the user can optionally point to a record in another table. Each autocomplete would need to work on the html element idfield_guid.
I'm imagining using jquery to enumerate the elements and add the autocomplete to each one with the target being the unique of field for that row. Another thought is a regex that maybe let you enumerate the fields and add autocomplete for each in a loop where the unique field id is handled automatically.
Does that sound reasonable or can you suggest the right way? Also is there a reasonable limit to how many autocomplete on a page? Thanks for any suggestions!
Edit, here's what I have after the help. data-jsonurl is apparently not being picked up by jquery as it is doing the html request to the url of the main page.
$(document).ready(function () {
var options = {
source: function(request, response) {
$.getJSON($(this).data("jsonurl"), request, function (return_data) {
response(return_data.itemList);
});
},
minLength: 2
};
$('.ac').autocomplete(options);
});
<%= Html.TextBoxFor(
x => x.AssetId,
new {
#class = "ac",
data_jsonurl = Url.Action("AssetSerialSearch", "WoTran", new { q = Model.AssetId })
})
%>
And the emitted html look okay to me:
<input class="ac" data-jsonurl="/WoTran/AssetSerialSearch?q=2657" id="WoTransViewModel_f32dedbb-c75d-4029-a49b-253845df8541__AssetId" name="WoTransViewModel[f32dedbb-c75d-4029-a49b-253845df8541].AssetId" type="text" value="2657" />
The controller is not a factor yet, in firebug I get a request like this:
http://localhost:58182/WoReceipt/Details/undefined?term=266&_=1312892089948
What seems to be happening is that the $(this) is not returning the html element but instead the jquery autocomplete widget object. If I drill into the properties in firebug under the 'element' I eventually do see the data-jsonurl but it is not a property of $(this). Here is console.log($this):
You could use the jQuery UI Autocomplete plugin. Simply apply some know class to all fields that require an autocomplete functionality as well as an additional HTML5 data-url attribute to indicate the foreign key:
<%= Html.TextBoxFor(
x => x.Name,
new {
#class = "ac",
data_url = Url.Action("autocomplete", new { fk = Model.FK })
})
%>
and then attach the plugin:
var options = {
source: function(request, response) {
$.getJSON($(this).data('url'), request, function(return_data) {
response(return_data.suggestions);
});
},
minLength: 2
});
$('.ac').autocomplete(options);
and finally we could have a controller action taking two arguments (term and fk) which will return a JSON array of suggestions for the given term and foreign key.
public ActionResult AutoComplete(string term, string fk)
{
// TODO: based on the search term and the foreign key generate an array of suggestions
var suggestions = new[]
{
new { label = "suggestion 1", value = "suggestion 1" },
new { label = "suggestion 2", value = "suggestion 2" },
new { label = "suggestion 3", value = "suggestion 3" },
};
return Json(suggestions, JsonRequestBehavior.AllowGet);
}
You should also attach the autocomplete plugin for newly added rows.

Categories

Resources