Im new with MVC.
I have a model called UAV.
│Callsign│NumDeliveries│Mileage│MaxVelocity│MinVelocity│
Hawk61 37 96 20 10
BURL14 2047 57 30 15
OTTO93 82 72 25 10
in cshtml file, i made a table only using Callsign, NumDeliveries, Mileage.
<table class="UAV_table" id="UAV_table">
<tr>
<th>Callsign</th>
<th>NumDeliveries</th>
<th>Mileage</th>
</tr>
#foreach (UAV uav in Model.UAVs)
{
<tr onclick="click_row()">
<td onclick="click_row()">
#Html.DisplayFor(modelItem => uav.Callsign)
</td>
<td>
#Html.DisplayFor(modelItem => uav.NumDeliveries)
</td>
<td>
#Html.DisplayFor(modelItem => uav.Mileage)
</td>
</tr>
}
</table>
so the table shows all datas for Callsign, NumDeliveries, Mileage.
what i want to do is, when i click the row of the table, i want to see only that correspond information.
#foreach (UAVs uavid in Model.uavs)
{
<p class="detail_title" id="detail_title">
UAV: # (#Html.DisplayFor(modelItem => uavid.MaxVelocity))
</p>
}
for example, using above line of code, if i click first row of that table(callsign = Hawk61), i want to see like UAV: # 20 (MaxVelocity for Hawk61). MaxVelocity is not in the table, so i need to get it from database.
But I have problem with showing data. If i use right above code, it has #foreach statement, it shows all the Hawk61, BURL14, OTTO93's MaxVelocity.
it shows me like
UAV:# 20
UAV:# 30
UAV:# 25
I need to see only what i selected. (just shows what i click, in this example, only need to show UAV:# 20 which is first row, Hawk61's MaxVelocity).
is there any way to get the data from database not using foreach statement?
Thank you.
Since the values of MaxVelocityand MinVelocity are populated, you can make use of data- attributes to store the values in the DOM and use jquery to display them. For example
#foreach (UAV uav in Model.UAVs)
{
<tr class="uavrow" data-maxvelocity="#uav.MaxVelocity" data-minvelocity="#MinVelocity">
<td>#Html.DisplayFor(modelItem => uav.Callsign)</td>
<td>#Html.DisplayFor(modelItem => uav.NumDeliveries)</td>
<td>#Html.DisplayFor(modelItem => uav.Mileage)</td>
</tr>
}
And include some elements to display the associated data when you click on the row
<div>
<div><span>Call Sign: </span><span id="callsign"></span>
<div><span>Max Velocity: </span><span id="maxvelocity"></span>
<div><span>Min Velocity: </span><span id="minvelocity"></span>
</div>
And the script
$('.uavrow').click(function) {
// Get the call sign for the td element
$('#callsign').text($(this).children('td').eq(0).text());
// Get the velocity from the data attributes
$('#maxvelocity').text($(this).data('maxvelocity'));
$('#minvelocity').text($(this).data('minvelocity'));
});
If however the value were not populated, or you have a large number of properties to display, then it may be better to make an ajax call to a method (passing the callsign) which returns a partial view containing the details
<div id="uavdetails"></div>
$('.uavrow').click(function) {
var callSign = $('#callsign').text($(this).children('td').eq(0).text());
var url = '#Url.Action("Details", "YourController")';
$('#uavdetails').load(url, { CallSign: callsign });
});
Controller
public ActionResult Details(string CallSign)
{
UAV uav = // Get the UAV base on the CallSign value
return PartialView(uav);
}
Actually you have all data that you need in there.
The only thing that you need is to show proper item by using JavaScript.
You need to add parameter to your function call here:
<tr onclick="click_row('#uav.Callsign')">
And also add css class here:
#foreach (UAVs uavid in Model.uavs)
{
<p class="detail_title #uavid.Callsign" id="detail_title" style="display=none;">
UAV: # (#Html.DisplayFor(modelItem => uavid.MaxVelocity))
</p>
}
And then add a bit of javascript:
<script>
function click_row(elClass){
var elements = document.getElementsByClassName("detail_title");
for (i = 0; i < x.length; i++) {
if(x[i].className.contains(elClass)){
x[i].style.display = 'block';
} else{
x[i].style.display = 'none';
}
}
};
<script/>
Related
I have been wondering why I can't alert a simple string in my function. This is my code:
<script>
function getData(str) {
alert(str);
}
</script>
//This is the code in the body,
I just want to print a simple awe to test if the onClick can recognize the value I pass in name; but whenever onClick method happens, the web only alert an empty string.
#foreach (var item in Model) {
var name = "awe";
<tr>
<td></td>
<td>#Html.DisplayFor(modelItem => item.DiscountDescs)</td>
<td>#Html.DisplayFor(modelItem => item.DiscountForm)</td>
<td>#Html.DisplayFor(modelItem => item.DiscountType)</td>
<td>#Html.DisplayFor(modelItem => item.DiscountMode)</td>
<td>#Html.DisplayFor(modelItem => item.DiscountValue)</td>
<td>#Html.DisplayFor(modelItem => item.IsActive)</td>
<td>#Html.DisplayFor(modelItem => item.IsScheme)</td>
</tr>
}
Change this:
<a href="#" onclick="getData(name);">
to:
<a href="#" onclick="getData('#name');">
name is nothing in this context, you have to put # for the c# variable.In view when we need to write c# code we write it with leading # sign:
For Example:
#foreach (var item in Model)
{
var name ="awe";
<tr>
<td>#name</td>
</tr>
}
If your intention is to include var name = "awe"; as a JavaScript variable, you need to put it in a <script> element:
<script>
var name = "awe";
</script>
I have a Kendo grid on a MVC .cshtml view page:
#model IEnumerable<Models.GetItems>
<script>
$(document).ready(function () {
$("#grid").kendoGrid({
sortable: true
});
});
</script>
<table class="table" id="grid">
<thead>
<tr>
<th data-field="Quantity">
Qty
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.ActionLink(item.Quantity.ToString(), "kendo", "Groups", new { ID = item.ID }, null)
</td>
</tr>
}
</tbody>
</table>
It displays the way I want; as a number with a link to a drill down page, but the sorting doesn't work at all.
How can I tell the grid I want the data type to be a number so it can sort it like a number?
(item.Quantity is Int16 from the model, but had to make it a string for the ActionLink to work)
(I'm open to binding the grid differently if I have to (bind to json output from controller and/or use rowTemplate and/or bind to empty div and define columns in JS possibly with template), but not sure at this point if that will matter, seems like a data type issue regardless of binding method???)
I have this view where I create a new company that gets added to the database.
The view is in 2 sections, leftside and rightside.
In the rightside I want to input the trades for that company.
A company can have 1 or more trade and this includes 1 primary trade, and 0 to many other trades.
When the user adds in the other trades, each trade will be added to a list underneath. I have NOT put in the code for this yet. For each trade in the list, he can have the option of removing it.
When he has entered all the details, he clicks submit and all the data is saved in the database.
Now I am thinking of putting in a partial view for the other trades, but I am wondering how I can do this, and every time a trade is selected from autocomplete, the data is posted to a controller method and the partial view is return.
But this will clear the data in the leftside section.
So how should I do this?
My view looks like
#model SCD.ViewModels.SubcontractorViewModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Create Subcontractor</legend>
<section class="wrapper">
<section class="leftside">
<table class="formTable">
<tr>
<td class="leftCell">#Html.LabelFor(model => model.Subcontractor.CompanyName)</td>
<td class="rightCell">#Html.TextBoxFor(model => model.Subcontractor.CompanyName, new { #style = "width: 300px;" })</td>
</tr>
<tr>
<td class="leftCell">#Html.LabelFor(model => model.AddressViewModel.Address1)</td>
<td class="rightCell">#Html.TextBoxFor(model => model.AddressViewModel.Address1, new { #style = "width: 300px;" })</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;" class="rightCell"><input type="submit" value="Save"/></td>
</tr>
</table>
<div style="float: left">#Html.ActionLink(" ", "List", null, new { #class = "buttonBackToList" })</div>
</section>
<section class="rightside">
<table class="formTable">
<tr>
<td class="leftCell">#Html.LabelFor(model => model.PrimaryTrade)</td>
<td class="rightCell"><input type="search" name="searchPrimaryTrade" id="searchPrimaryTrade" data-scd-autocomplete="#Url.Action("AutocompletePrimaryTrade", "DataService")" style = "width: 300px;"/>
<input type="button" id="ResetPrimaryTrade" value="Reset"/>
</td>
</tr>
<tr>
<td class="leftCell">#Html.LabelFor(model => model.OtherTrades)</td>
<td class="rightCell"><input type="search" name="searchOtherTrade" id="searchOtherTrade" data-scd-autocomplete="#Url.Action("AutocompleteOtherTrade", "DataService")" style = "width: 300px;"/>
<input type="button" id="ResetOtherTrade" value="Reset"/>
</td>
</tr>
</table>
</section>
</section>
</fieldset>
}
Ajax is your answer, Whenever you do not want to reload the page then using client side ajax to communicate with the server is the only option.
I would use jQuery or to add the rows via ajax which will insert them into your database and return the populated model again and return this as a PartialView(). Your ajax would then onSuccess: replace your tableID with the returned results.
So your jQuery would be something like:
$('.rightside').children('.formTable').replaceWith(theReturnedPartialFromAjaxCall);
If you are adding a dynamic row there are two options:
On adding a row you can call an ajax request which will also add a blank row to the database and then repopulate your model and return the Partial View. This will now have the model binding in place on the new blank row, deleting the blank row or any row can also be done by ajax as the row now has an ID. Make sure however you put the ID as a hidden field in when you loop through each row.
OR (not the preferred way but probably what you will need to do as you have to perform the save)
You can capture the form collection in the save, if there are multiple rows then store this in an array
public ActionResult Save(MyModel model, FormCollection frm) {
String[] name = frm["name"].Split(',');
}
I don't like this way as it is prone to error and the first method will allow you to bind MVC's model validation
<tr>
#foreach (string s in "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15".Split(','))
{
<td>#Html.TextBox("Time","")
</td>
<p>
</p>
}
</tr>
How i get the values from textboxes created above using either javascript or jquery.
kindly assist me
Here it is:
$('input[name=Time]').each(function(index, element){
var txtValue = element.value;
});
I'm iterating a List<T> in a razor foreach loop in my view which renders a partial. In the partial I'm rendering a single record for which I want to have 4 in a row in my view. I have a css class for the two end columns so need to determine in the partial whether the call is the 1st or the 4th record. What is the best way of identifying this in my partial to output the correct code?
This is my main page which contains the loop:
#foreach (var myItem in Model.Members){
//if i = 1
<div class="grid_20">
<!-- Start Row -->
//is there someway to get in for i = 1 to 4 and pass to partial?
#Html.Partial("nameOfPartial", Model)
//if i = 4 then output below and reset i to 1
<div class="clear"></div>
<!-- End Row -->
</div>
}
I figure I can create a int that I can update on each pass and render the text no problem here but it's passing the integer value into my partial I'm more concerned about. Unless there's a better way.
Here is my partial:
#{
switch()
case 1:
<text>
<div class="grid_4 alpha">
</text>
break;
case 4:
<text>
<div class="grid_4 omega">
</text>
break;
default:
<text>
<div class="grid_4">
</text>
break;
}
<img src="Content/960-grid/spacer.gif" style="width:130px; height:160px; background-color:#fff; border:10px solid #d3d3d3;" />
<p>#Model.Name<br/>
#Model.Job<br/>
#Model.Location</p>
</div>
Not sure if I'm having a blonde day today and this is frightfully easy but I just can't think of the best way to pass the int value in. Hope someone can help.
#{int i = 0;}
#foreach(var myItem in Model.Members)
{
<span>#i</span>
i++;
}
//this gets you both the item (myItem.value) and its index (myItem.i)
#foreach (var myItem in Model.Members.Select((value,i) => new {i, value}))
{
<li>The index is #myItem.i and a value is #myItem.value.Name</li>
}
More info on my blog post
http://jimfrenette.com/2012/11/razor-foreach-loop-with-index/
Or you could simply do this:
#foreach(var myItem in Model.Members)
{
<span>#Model.Members.IndexOf(myItem)</span>
}
Take a look at this solution using Linq. His example is similar in that he needed different markup for every 3rd item.
foreach( var myItem in Model.Members.Select(x,i) => new {Member = x, Index = i){
...
}
You could also use deconstruction and tuples and try something like this:
#foreach (var (index, member) in #Model.Members.Select((member, i) => (i, member)))
{
<div>#index - #member.anyProperty</div>
if(index > 0 && index % 4 == 0) { // display clear div every 4 elements
#: <div class="clear"></div>
}
}
For more info you can have a look at this link
Is there a reason you're not using CSS selectors to style the first and last elements instead of trying to attach a custom class to them? Instead of styling based on alpha or omega, use first-child and last-child.
http://www.quirksmode.org/css/firstchild.html
IndexOf seems to be useful here.
#foreach (myItemClass ts in Model.ItemList.Where(x => x.Type == "something"))
{
int currentIndex = Model.ItemList.IndexOf(ts);
#Html.HiddenFor(x=>Model.ItemList[currentIndex].Type)
...
All of the above answers require logic in the view. Views should be dumb and contain as little logic as possible. Why not create properties in your view model that correspond to position in the list eg:
public int Position {get; set}
In your view model builder you set the position 1 through 4.
BUT .. there is even a cleaner way. Why not make the CSS class a property of your view model? So instead of the switch statement in your partial, you would just do this:
<div class="#Model.GridCSS">
Move the switch statement to your view model builder and populate the CSS class there.
Very Simple:
#{
int i = 0;
foreach (var item in Model)
{
<tr>
<td>#(i = i + 1)</td>`
</tr>
}
}`
In case you want to count the references from your model( ie: Client has Address as reference so you wanna count how many address would exists for a client) in a foreach loop at your view such as:
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.DtCadastro)
</td>
<td style="width:50%">
#Html.DisplayFor(modelItem => item.DsLembrete)
</td>
<td>
#Html.DisplayFor(modelItem => item.DtLembrete)
</td>
<td>
#{
var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();
}
<button class="btn-link associado" data-id="#item.IdLembrete" data-path="/LembreteEnvolvido/Index/#item.IdLembrete"><i class="fas fa-search"></i> #contador</button>
<button class="btn-link associar" data-id="#item.IdLembrete" data-path="/LembreteEnvolvido/Create/#item.IdLembrete"><i class="fas fa-plus"></i></button>
</td>
<td class="text-right">
<button class="btn-link delete" data-id="#item.IdLembrete" data-path="/Lembretes/Delete/#item.IdLembrete">Excluir</button>
</td>
</tr>
}
do as coded:
#{ var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();}
and use it like this:
<button class="btn-link associado" data-id="#item.IdLembrete" data-path="/LembreteEnvolvido/Index/#item.IdLembrete"><i class="fas fa-search"></i> #contador</button>
ps: don't forget to add INCLUDE to that reference at you DbContext inside, for example, your Index action controller, in case this is an IEnumerable model.
I prefer to use this extension method:
public static class Extensions
{
public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> self)
=> self.Select((item, index) => (item, index));
}
Source:
https://stackoverflow.com/a/39997157/3850405
Razor:
#using Project.Shared.Helpers
#foreach (var (item, index) in collection.WithIndex())
{
<p>
Name: #item.Name Index: #index
</p>
}