I try to make an if function in razor view, by comparing two data from viewbag in ASP NET MVC
#ver comes from ViewBag.Temp
<td class="text-center">
#foreach (Dummy ver in ViewBag.dummies)
{
if (#ver.Name == #item.Name)
{
<i class="fas fa-check" id="existed"></i>
}
}
</td>
I already have 2 same name data inside those 2 tables but it wont work
The Temp data
The Dummies Data
but when i call another data it works properly
Another data temp
Another data Dummies
It solved, there is some human error on the data that have white space on leading or trailing then im using trim() function on my view
look like this
<td class="text-center">
#foreach (Dummy ver in ViewBag.Dummies)
{
var tem = #item.Name.Trim();
if (#ver.Name.Trim() == tem)
{
<i class="fas fa-check" id="existed"></i>
}
}
</td>
Related
I have a HTML table with 2 rows and 4 columns. The data in each cell is coming from the stored proc. Currently, the last column displays number, I have an image to display, but it has to be displayed only if(rejected_question>0) else it should not display anything. How do I accomplish this in razor.
I have tried this so far, the below code doesn't work:
#foreach (var item in Model)
{
//logic for first three columns..
//fourth column here.
<td align="center">
if(#Html.DisplayFor(modelItem => item.RejectedQuestion) >0)
{
return Html.Raw(string.Format("<text><img height='3' width='3' src="\{0}\" alt="\Image\" /></text>", Url.Content("../../content/images/icon_red_questions_returnedbyreviewer.gif")));
}
</td>
}
This is what your looking for, probably:
#foreach (var item in Model)
{
//logic for first three columns..
//fourth column here.
<td align="center">
#if(item.RejectedQuestion > 0)
{
<img height="3" width="3" alt="Image"
src="#Url.Content("~/content/images/icon_red_questions_returnedbyreviewer.gif")" />
}
</td>
}
Make the line inside the if statement
#Html.Raw(string.Format("<text><img height='3' width='3' src="\{0}\" alt="\Image\" /></text>", Url.Content("../../content/images/icon_red_questions_returnedbyreviewer.gif")))
to display it. view.Execute() returns void, so you cannot include a return statement.
I tried this and it worked, just in case if someone needs it in future
:
#if(item.RejectedQuestion > 0)
{
<img height="20" width="20" alt="Image"
src="#Url.Content("~/content/images/icon_red_questions_returnedbyreviewer.gif")" />
}
I need to send send value of particular row to controller method on clicking of anchor buttons. Also I need functionality to filter data based on dropdown selection(Working fine). I am newbie to asp mvc, Do not know if I am doing right if there is any BETTER solution without Jquery tables please suggest.
Here is my view structure:
#using (Html.BeginForm("Index", "Manage_Menu", FormMethod.Post, new { id = "myForm" }))
{<div style="float:left;padding-bottom:10px;">
<b>Select Parent Page</b>
<div>
#Html.DropDownList("ddlPageId", (IEnumerable<SelectListItem>)ViewBag.PageDDL, "Select parent page", new { onchange = "this.form.submit();" })
</div>
</div>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.PageName)
</th>
<th>
#Html.DisplayNameFor(model => model.IsActive)
</th>
<th>
#Html.DisplayNameFor(model => model.ShowInMenu)
</th>
<th>Move Menu Position</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.PageName)
</td>
<td>
<a href="javascript:void()" onclick="sumitForm()">
<input type="hidden" name="mmmm" value="#item.Id" />
#if (item.ShowInMenu == true)
{
<span class="glyphicon glyphicon-ok text-success" aria-hidden="true"></span>
}
else
{
<span class="glyphicon glyphicon-remove text-danger" aria-hidden="true"></span>
}
</a>
</td>
<td>
<a href="javascript:void()" onclick="sumitForm()">
#if (item.ShowInMenu == true)
{
<span class="glyphicon glyphicon-ok text-success" aria-hidden="true"></span>
}
else
{
<span class="glyphicon glyphicon-remove text-danger" aria-hidden="true"></span>
}
</a>
</td>
<td>
<a href="javascript:void()" onclick="sumitForm()">
<span class="glyphicon glyphicon-arrow-up" aria-hidden="true"></span>
</a>
<a href="javascript:void()" onclick="sumitForm()">
<span class="glyphicon glyphicon-arrow-down" aria-hidden="true"></span>
</a>
</td>
</tr>
}
</table>
<script>
function sumitForm() {
document.getElementById("myForm").submit();
}
</script>
}
Here is my Controller:
public ActionResult Index()
{
var pages = db.PageMains.Where(a => a.ParentPageId == 0); ;
ViewBag.PageDDL = new SelectList(db.PageMains.Where(r => r.ParentPageId == 0), "Id", "PageName");
return View(pages);
}
[HttpPost]
public ActionResult Index(FormCollection aa)
{
if (!string.IsNullOrEmpty(aa["ddlPageId"]))
{
int filter = Convert.ToInt32(aa["ddlPageId"]);
var pages = db.PageMains.Where(a => a.ParentPageId == filter);
ViewBag.PageDDL = new SelectList(db.PageMains.Where(r => r.ParentPageId == 0), "Id", "PageName", filter);
return View(pages);
}
else
{
var pages = db.PageMains.Where(a => a.ParentPageId == 0); ;
ViewBag.PageDDL = new SelectList(db.PageMains.Where(r => r.ParentPageId == 0), "Id", "PageName");
return View(pages);
}
}
I have tried to store values inside hidden field but whenever I press any anchor button it is sending all the values.
Here is my page design:
What #Stephen Muecke is suggesting is the ideal situation to update the content in one action.
However, sometimes we need to update content in real time. So to handle your case jQuery is the best bet. Since you asked to do it using MVC, below is the proposed solution (Ironically, under the hood jQuery is doing the work for you)
You need to use #Ajax.ActionLink method provided in MVC to make ajax calls. To make it a real Ajax, you need to add reference to jquery.unobtrusive-ajax.min.js. Otherwise it will fallback to Postback request
E.g.
Script Reference needs to be added.
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
Your action button in view would look like:
#Ajax.ActionLink("Click Me", "Clicked", "Home", new { id = item.pageId})
Action Method
public void Clicked(string id)
{
//Save the page ID in database. I keep it simple but if you want, you can return the status too.
}
One drawback of using #Ajax.ActionLink is, you cannot set html inside anchor tag like you did in your example (e.g. span tag). If you want to achieve that too refer here
The problem here is that you have a single form and all the anchors have the code to submit the form on click. So your click on any of the anchors lead to entire form submission - hence submitting all the data.
If you want partial data submission you can very well use ajax post. Pass the value using the ajax post and based on the return from controller update the table.
Since you are new to the technology I would suggest taking some time to read about ajax posts: https://api.jquery.com/jquery.post/
Also for more dynamic client side bindings you can use client side frameworks like AngularJS
OR
A very bad way would be to have forms for all the rows and name them based on the element's Id and on click submit only the form specific to the row. But this would be pathetic code.
I'm building an angularjs / firebase app unsing the angularfire bindings (v0.5.0).
I have a list of items, displayed in a table with ng-repeat on the <tr>, something like this:
<table>
<tbody>
<tr ng-repeat="(index, item) in items">
<td>
<input type="checkbox" ng-model="item.done">
</td>
<td>
<input type="text" ng-model="item.text" ng-focus="onItemFocus(index)" ng-blur="onItemBlur(index)">
</td>
<td>
<button type="button" ng-click="remove(index)">×</button>
</td>
</tr>
</tbody>
</table>
and there's an angularfire 3 way data binding on this list of items, something like:
$scope.ref = new Firebase('...');
$scope.remote = $firebase($scope.ref);
$scope.remote.$child("items").$bind($scope, "items");
This works all fine, but now I'm trying to add the possibility to reorder the items with drag and drop.
I managed to setup the drag and dropping UI with jquery-ui (essentially calling $("tbody").sortable()), but my problem is to bind it to the angular models. There's a number of questions regarding that (with great jsfiddles) but in my case the angularfire 3 way binding seems to be messing it up.
I think I need to use firebase priorities with angularfire's orderByPriority and maybe deal with it in one of the sortable callbacks but I'm having trouble figuring out exactly how I should do that... and can't find any sort of documentation about it.
Has anyone done something similar, and could you share some pointers on how to set this up?
I saw your post a long time ago while I was looking for the same solution. Here is something I put together:
function onDropComplete(dropIndex, item) {
if (!item.isNew){
var dragIndex = $scope.fireData.indexOf(item);
item.priority = dropIndex;
$scope.fireData.$save(dragIndex);
if (dragIndex > dropIndex){
while ($scope.fireData[dropIndex] && dropIndex !== dragIndex ){
$scope.fireData[dropIndex].priority = dropIndex+1;
$scope.fireData.$save(dropIndex);
dropIndex++;
}
} else if(dragIndex < dropIndex){
while ($scope.fireData[dropIndex] && dropIndex !== dragIndex ){
$scope.fireData[dropIndex].priority = dropIndex-1;
$scope.fireData.$save(dropIndex);
dropIndex--;
}
}
} else if (item.isNew){
item = angular.copy(item);
item.isNew = false;
item.priority = dropIndex;
$scope.fireData.$add(item);
while ($scope.fireData[dropIndex]){
$scope.fireData[dropIndex].priority = dropIndex+1;
$scope.fireData.$save(dropIndex);
dropIndex++;
}
}
}
Here, I take items already in the list and have the priority properties of items adjust on drop, depending if the item that was dragged was above or below the drop area. Also, if the drag item in new to the list, it will be added at index where dropped and all items below will be bumped up 1 priority. This is dependent on having your list sorted by var sync = $firebase(ref.orderByChild('priority'));, and you to be using ngDraggable.
Here is some HTML for an example:
<tr ng-repeat="obj in fireData" ng-drop="true" ng-drop-success="onDropComplete($index, $data,$event)">
<td draggable="true" ng-drag="true" ng-drag-data="obj">
<span class="glyphicon glyphicon-move"></span><div class="drag-name">{{obj.name}}</div>
</td>
<td>{{obj.name}}</td>
<td>{{obj.type}}</td>
<td><input type="checkbox" ng-change="saveChanges(obj)" ng-model="obj.completed"></td>
<td>
<div class="" ng-click="deleteItemFromList(obj)">
<span class="glyphicon glyphicon-remove"></span>
</div>
</td>
</tr>
I am using angularJS ontop of my application.
I have a basic example of a controller:
function OrderListCtrl($scope, $http) {
$http.get('/static/angular/app/phones/van1.json').success(function(data) {
$scope.van1 = data;
});
$http.get('/static/angular/app/phones/van2.json').success(function(data) {
$scope.van2 = data;
});
}
And a sample JSON entry
{
"id": "3",
"custName": "Mrs Smith",
"accountNumber": "416",
"orderNumber": "12348",
"orderWeight": "120.20"
},
My html looks like this:
<div id=1>
<h1>Van 1 - Total Weight = XXX </h1>
<ul class="sortdrag">
<li ng-repeat="van1 in van1" id="[[ van1.id ]]">
[[van1.custName]] [[van1.accountNumber]] [[van1.orderWeight]]
</li>
</ul>
</div>
Now, I want to get the total weight for every li item in the ul.
This WOULD be easy if the lists where static, however the lists are using jQuery-ui and I have multiple lists where the li items are dragged and dropped between each list. My question is, how can I have the XXX dynamically update to the value of all weights in each li in the ul, or more to the question can this even be done?
I dont really want to use an onDrop event as this will not work on the pre-populated lists, so ideally I would like to use code that takes its values from all van1.orderWeight values in the ul.
Any suggestions on the best way to approach this would be very much appreciated! And before anyone asks im using [[ and ]] as opposed to {{ and }} because I am using jinja2 templates.
UPDATE:
Ok to after reading the answer below have amended the original controller to:
function OrderListCtrl($scope, $http) {
$http.get('/static/angular/app/phones/van1.json').success(function(data) {
$scope.van1 = data;
// This part is easy, calcuate the sum of all weights from the JSON data
$scope.sumV1 = _.reduce(_.pluck($scope.van1, 'orderWeight'), function (m, w) {return m + w}, 0);
});
$scope.getVan1Weight = function(){
// here I try and write a function to calculate the dynamic weight
// of a van, which will update when items get dropped in/out of the ul
_.reduce(_.pluck($scope.van1, 'orderWeight'), function (m, w) {return m + w}, 0);
}
And my template
<div id="app" ng-controller="OrderListCtrl">
<div id=1>
<h1>Van 1 - Total Weight = [[getVan1Weight()]]
Starting Weight - [[sumV1]]</h1>
<ul class="sortdrag">
<li ng-repeat="van1 in van1" id="[[ van1.id ]]">
[[van1.custName]] [[van1.accountNumber]] [[van1.orderWeight]]
</li>
</ul>
</div>
Now im using the underscorejs libary to help perform the calculations, but I can only seem to get this to work using the initial data, and not to update when new orders are dragged in from another ul
That is pretty each to achieve in Angular. You have to write a function in your controller that does the calculation for you and interpolate that function in your view. Something like
<div id=1>
<h1>Van 1 - Total Weight = [[getVanWeight()]] </h1>
<ul class="sortdrag">
<li ng-repeat="van1 in vans" id="[[ van1.id ]]">
[[van1.custName]] [[van1.accountNumber]] [[van1.orderWeight]]
</li>
</ul>
</div>
Inside your controller you do :
$scope.getVanWeight = function(){
// write your logic for calculating van weight here.
}
Thanks to #ganaraj I used the guide found at
http://www.smartjava.org/content/drag-and-drop-angularjs-using-jquery-ui
I also replaced my underscore code with pure angularjs code
$scope.getVan1Weight = function(){
var sum = 0;
for( t=0; t < $scope.van1.length; t++) { sum += $scope.van1[t].orderWeight }
return sum.toFixed(2);;
}
At the beginning of my controller I also defined an empty array (to get overwritten later)
// Define an empty array
$scope.van1 = [];
As this stops any errors producing as the $http get takes a while to load and when you load a browser window the .length returns an error, so if you define an empty array it stops any errors. I could have tested to see if an array was valid and put some if clauses in, but my angularjs knowledge is very limited so this solution worked best for me.
Here's something very similar to your requirement with a solution that works nicely...
Markup...
<table class="table table-condensed table-striped">
<thead>
<tr>
<th>Pillar Name</th>
<th>Weight</th>
<th>Metrics</th>
<th> Actions</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="p in l.pillars">
<td>{{p.name}}</td>
<td>{{p.weight}}</td>
<td>{{p.metrics.length}}</td>
<td>
<a href="" data-ng-click="vm.editPillar(p)">
<i class="fa fa-pencil blue"></i>
</a>
<a href="" data-ng-click="vm.deletePillar(p, l)">
<i class="fa fa-times-circle red"></i>
</a>
</td>
</tr>
<tr>
<td><strong>Totals</strong></td>
<td><strong>{{l.pillars.summedWeight}}</strong></td>
<td></td>
<td></td>
</tr>
</tbody>
js, which gets called when i get pillars from the server or local cache...
function getSummedPillarWeight(pillars) {
var summedWeight = 0;
pillars.forEach(function (pillar) {
summedWeight = summedWeight + pillar.weight;
});
return pillars.summedWeight = summedWeight;
}
On an ASP.NET MVC View, I have a couple of checkboxes, one for email address and one for phone. I want to make sure that at least one is checked (both can be checked, so a radio button is not ideal) and if neither are, highlight the row with a red border just like a textbox is with the validation functionality...
I have other fields that are getting validated correctly and the CSS is changing when there is an issue on the textboxes and textareas accordingly. The code below displays the message informing the user they must specify a contact preference, but does not highlight the row as having an issue...
SCREEN SHOT
VIEW
<table width="100%">
<tr>
<td>
<label>
How would you like us to contact you?
</label>
</td>
</tr>
<tr id="pref_row">
<td>
<span class="bold-text">Email: </span>
<%=Html.CheckBox("EmailDesired")%>
<span class="bold-text">Phone: </span>
<%=Html.CheckBox("PhoneDesired")%>
</td>
</tr>
</table>
CONTROLLER
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(ContactUs contactus)
{
ContactUsService svc = new ContactUsService();
// Validation
if (!contactus.EmailDesired && !contactus.PhoneDesired)
ViewData.ModelState.AddModelError("pref_row", "Please specify a contact preference (phone and/or email)!");
if (ViewData.ModelState.IsValid)
{
MessageModel msg = svc.SendRequest(contactus);
return RedirectToAction("Index", msg);
}
else
{
return View();
}
}
When the HtmlHelper render itself it checks if there is any item in the ModelState dictionary that has the same key as the helper itself. if so the control will be rendered with the attribute class equal to "input-validation-error" which is defined in the css file.
So, the style will be applied only on the rendered input controls.
This is my solution:
<table width="100%">
<tr>
<td>
<label>
How would you like us to contact you?
</label>
</td>
</tr>
<tr class="<%=ViewData.ModelState["pref_row"]!= null ? "input-validation-error":"" %>">
<td>
<span class="bold-text">Email: </span>
<%=Html.CheckBox("EmailDesired")%>
<span class="bold-text">Phone: </span>
<%=Html.CheckBox("PhoneDesired")%>
</td>
</tr>
</table>