How can I check string value in razor view? - asp.net-mvc

I have a model, and I want to show dome data, if table_name == "something". All data are different, that is why I need to check. but when I write ==, my View does not understand. It returns only else clause data.
Please help me, how can I check the string value in view?
#foreach (var item in Model)
{
if (item.table_name == "tPerson")
{ #item.user_group_name: <strong>#item.user_full_name</strong> | #item.date;
}
else if (item.table_name == "tBook")
{ Book<strong>#item.book_name</strong> | #item.date}
else
{#item.table_name <strong>#item.name</strong> | #item.date}
}

Check out the "item.table_name" has the back Space or front space

Related

Angular2 How to Handle null value in .find methode

Here i wrote simple .find method its finding my data well but if that record is not available then its displying 1st Record
public _pagedItems : any;
someval(value){
if(value.length>=5){
this._pagedItems= this.allItems.find(e=>e.uniqueid = value);
this.pagedItems=[];
this.pagedItems.push(this._pagedItems);
}
if my uniquId is not avaible then its should display Nodata OR Null
Here is an example for handle null and undefined and return no data like
Your code is looking wrong. Your are code using (=) symbol. So change (==).
The difference between = and == (=) equal symbol is assigning value (==) symbol is comparing a value
For more proper example here,
public _pagedItems : any[]=[];
someval(value:string){
if(!this.isObjNull(value) && !this.isObjNull(this.allItems) && this.allItems.length>0){
if(value.length>=5){
if(this.allItems.find(e=>e.uniqueid ==value)){
//you need one data use find
this._pagedItems=this.allItems.find(e=>e.uniqueid == value);
//you need multiple data use filter
this._pagedItems = this.allItems.filter(e=>e.uniqueid == value);
}
//here Iam logged final variable
console.log("Final Paged Items",this._pagedItems);
}
}
}
//here is the method check null and undefined.
isObjNull(data){
If(data!=null && data!=undefined){
return true:
}else{
return false;
}
}
You can handle html part like this
<ng-container *ngIf="_pagedItems; else noData">
<ng-container *ngIf="_pagedItems.length>0; else noData">
<!-- do you logic here.like *ngFor -->
</ng-container>
</ng-container>
<ng-template #noData>
<p>No data found</p>
</ng-template>
That's all let try this once. If any error please let me know.
Note:- here Iam used sample variable please replace your actual variable.
For comparison related more thing visit here.
Difference between == and === in JavaScript

Soft deletion in mvc

I want to soft delete, no records are physically deleted from the database, just sets the IsDeleted filed to true.It would be more than one data with that value. In controller I add:
var res = (from c in db.Books
where c.IsDeleted == 1
select c);
And I don't know how to add a condition to a if clause. Tried
if (res != 1){
return View(db.Books.ToList());
}
but it isn't. Has anyone have an idea what to do?
== checks for equality. if you want to set the IsDeleted field, you need something slightly different
try something like
var res = (from c in db.Books
where c.Id == IdToFind).SingleOrDefault().IsDeleted = 1;
Disclaimer: Code may not be accurate, but should give ou an idea!

LINQ query with omitted user input

so I have a form with several fields which are criteria for searching in a database.
I want to formulate a query using LINQ like so:
var Coll = (from obj in table where value1 = criteria1 && value2 = criteria2...)
and so on.
My problem is, I don't want to write it using If statements to check if every field has been filled in, nor do I want to make separate methods for the various search cases (criteria 1 and criteria 5 input; criteria 2 and criteria 3 input ... etc.)
So my question is: How can I achieve this without writing an excessive amount of code? If I just write in the query with comparison, will it screw up the return values if the user inputs only SOME values?
Thanks for your help.
Yes, it will screw up.
I would go with the ifs, I don't see what's wrong with them:
var query = table;
if(criteria1 != null)
query = query.Where(x => x.Value1 == criteria1);
if(criteria2 != null)
query = query.Where(x => x.Value2 == criteria2);
If you have a lot of criteria you could use expressions, a dictionary and a loop to cut down on the repetitive code.
In an ASP.NET MVC app, chances are your user input is coming from a form which is being POSTed to your server. In that case, you can make use of strongly-typed views, using a viewmodel with [Required] on the criteria that MUST be provided. Then you wrap your method in if (ModelState.IsValid) { ... } and you've excluded all the cases where the user hasn't given you something they need.
Beyond that, if you can collect your criteria into a list, you can filter it. So, you could do something like this:
filterBy = userValues.Where(v => v != null);
var Coll = (from obj in table where filterBy.Contains(value1) select obj);
You can make this more complex by having a Dictionary (or Lookup for non-unique keys) that contains a user-entered value along with some label (an enum, perhaps) that tells you which field they're filtering by, and then you can group them by that label to separate out the filters for each field, and then filter as above. You could even have a custom SearchFilter object that contains other info, so you can have filters with AND, NOT and OR conditions...
Failing that, you can remember that until you trigger evaluation of an IQueryable, it doesn't hit the database, so you can just do this:
var Coll = (from obj in table where value1 == requiredCriteria select obj);
if(criteria1 != null)
{
query = query.Where(x => x.Value1 == criteria1);
}
//etc...
if(criteria5 != null)
{
query = query.Where(x => x.Value5 == criteria5);
}
return query.ToList();
That first line applies any criteria that MUST be there; if there aren't any mandatory ones then it could just be var Coll = table;.
That will add any criteria that are provided will be applied, any that aren't will be ignored, you catch all the possible combinations, and only one query is made at the end when you .ToList() it.
As I understand of your question you want to centralize multiple if for the sake of readability; if I were right the following would be one of some possible solutions
Func<object, object, bool> CheckValueWithAnd = (x, y) => x == null ? true : x==y;
var query = from obj in table
where CheckValue(obj.value1, criteria1) &&
CheckValue(obj.value2, criteria2) &&
...
select obj;
It ls flexible because in different situations or scenarios you can change the function in the way that fulfill your expectation and you do not need to have multiple if.
If you want to use OR operand in your expression you need to have second function
Func<object, object, bool> CheckValueWithOr = (x, y) => x == null ? false : x==y;

Conditional inside foreach inside conditional with Razor

I'm trying to learn Razor but have come up against a syntax problem. When I run the following code:
#if (searchTerm != ""){
<h2>Showing #ExamineManager.Instance.Search(searchTerm, true).Count() results for #searchTerm</h2>
<div class="search-results">
#foreach (var result in ExamineManager.Instance.Search(searchTerm, true)) {
if (result.Fields["nodeTypeAlias"] == 'File'){
<p>File</p>
}else{
<p>Not file</p>
}
}
</div>
}
this errors, saying "Too many characters in character literal". The actual mechanism of the code works, it's just a syntax problem with the way the conditionals are nested I think, but I've tried various combinations of #{} blocks and prepending # to various lines but just can't get it to work.
Can anyone see what I'm doing wrong?
Thanks!
'File' is invalid syntax. You probably meant "File" in your if condition when you want to work with strings:
if (result.Fields["nodeTypeAlias"] == "File")
That is because you've got comparison
result.Fields["nodeTypeAlias"] == 'File'
In c#, you cannot write strings into single quotes like that. You should change it into
result.Fields["nodeTypeAlias"] == "File"
Just change the Code In this way
#{
if (searchTerm != ""){
<h2>Showing #ExamineManager.Instance.Search(searchTerm, true).Count() results for #searchTerm</h2>
<div class="search-results">
foreach (var result in ExamineManager.Instance.Search(searchTerm, true)) {
if (result.Fields["nodeTypeAlias"] == 'File'){
<p>File</p>
}
else{
<p>Not file</p>
}
}
</div>
}
}
THis code will help you

ASP.MVC 1.0 Checkbox values with ViewModel and for specific ID

All,
I've read through a lot of posts about Checkboxes and ASP.MVC but I'm not that much wiser.
My scenario:
I have a strongly typed View where I pass a collection of summary objects to the view for rendering in a for-each. This summary object contains label data based on a unique id. I also add a checkbox to the row so do so via:
<td>
<%= Html.CheckBox("markedItem", Model.MarkedItem, new { TrackedItemId = Model.Id })%>
</td>
When I perform a POST to get the submitted results my action method takes the strongly typed ViewModel back but the original summary object that I used to create the list is not populated.
Ok, this is annoying, but I can understand why so I'll live with it.
What I then do is to add a new property to my ViewModel called "MarkedItem" which is a string collection.
On postback this marked item is filled with the before and after states if the checkbox has changed but nothing to tell me which key they were for. Just to clarify, if I send this
TrackedItemId = A, Value = false
TrackedItemId = B, Value = true
TrackedItemId = C, Value = false
and set the page to this:
TrackedItemId = A, Value = true
TrackedItemId = B, Value = true
TrackedItemId = C, Value = false
I will get back this:
MarkedItem[0] = true
MarkedItem[1] = false
MarkedItem[2] = true
MarkedItem[3] = false
in other words [0] is the new value and [1] is the old value, [2] and [3] represent values that haven't changed.
My questions are:
Is this right - that I get before and after in this way? Is there any way to only send the latest values?
How can I get hold of the custom attribute (TrackedItemId) that I've added so that I can add meaning to the string array that is returned?
So far I like MVC but it not handling simple stuff like this is really confusing. I'm also a javascript noob so I really hope that isn't the answer as I'd like to return the data in my custom viewmodel.
Please make any explanations/advice simple :)
<p>
<label>
Select project members:</label>
<ul>
<% foreach (var user in this.Model.Users)
{ %>
<li>
<%= this.Html.CheckBox("Member" + user.UserId, this.Model.Project.IsUserInMembers(user.UserId)) %><label
for="Member<%= user.UserId %>" class="inline"><%= user.Name%></label></li>
<% } %></ul>
and in the controller:
// update project members
foreach (var key in collection.Keys)
{
if (key.ToString().StartsWith("Member"))
{
int userId = int.Parse(key.ToString().Replace("Member", ""));
if (collection[key.ToString()].Contains("true"))
this.ProjectRepository.AddMemberToProject(id, userId);
else
this.ProjectRepository.DeleteMemberFromProject(id, userId);
}
}
With thanks to Pino :)
ok, one hack I've come up with - I really hate that I have to do this but I don't see another way round it and I'm sure it will break at some point.
I've already implemented by own ModelBinder to get round some other issues (classes as properties for example) so have extended it to incorporate this code. We use Guid's for all our keys.
If there are any alternatives to the below then please let me know.
Html
<%= Html.CheckBox("markedItem" + Model.Id, false)%>
C#
(GuidLength is a const int = 36, Left and Right are our own string extensions)
//Correct checkbox values - pull all the values back from the context that might be from a checkbox. If we can parse a Guid then we assume
//its a checkbox value and attempt to match up the model. This assumes the model will be expecting a dictionary to receive the key and
//boolean value and deals with several sets of checkboxes in the same page
//TODO: Model Validation - I don't think validation will be fired by this. Need to reapply model validation after properties have been set?
Dictionary<string, Dictionary<Guid, bool>> checkBoxItems = new Dictionary<string, Dictionary<Guid, bool>>();
foreach (var item in bindingContext.ValueProvider.Where(k => k.Key.Length > GuidLength))
{
Regex guidRegEx = new Regex(#"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$");
if (guidRegEx.IsMatch(item.Key.Right(GuidLength)))
{
Guid entityKey = new Guid(item.Key.Right(GuidLength));
string modelKey = item.Key.Left(item.Key.Length - GuidLength);
Dictionary<Guid, bool> checkedValues = null;
if (!checkBoxItems.TryGetValue(modelKey, out checkedValues))
{
checkedValues = new Dictionary<Guid, bool>();
checkBoxItems.Add(modelKey, checkedValues);
}
//The assumption is that we will always get 1 or 2 values. 1 means the contents have not changed, 2 means the contents have changed
//and, so far, the first position has always contained the latest value
checkedValues.Add(entityKey, Convert.ToBoolean(((string[])item.Value.RawValue).First()));
}
}
foreach (var item in checkBoxItems)
{
PropertyInfo info = model.GetType().GetProperty(item.Key,
BindingFlags.IgnoreCase |
BindingFlags.Public |
BindingFlags.Instance);
info.SetValue(model, item.Value, null);
}

Resources