#{int count = 0;}
#foreach (var item in Model.Resources)
{
#(count <= 3 ? Html.Raw("<div class=\"resource-row\">").ToString() : Html.Raw(""))
// some code
#(count <= 3 ? Html.Raw("</div>").ToString() : Html.Raw(""))
#(count++)
}
This code part does not compile, with the following error
Error 18 Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'System.Web.IHtmlString' d:\Projects\IRC2011_HG\IRC2011\Views\Home\_AllResources.cshtml 21 24 IRC2011
What I must I do?
Html.Raw() returns IHtmlString, not the ordinary string. So, you cannot write them in opposite sides of : operator. Remove that .ToString() calling
#{int count = 0;}
#foreach (var item in Model.Resources)
{
#(count <= 3 ? Html.Raw("<div class=\"resource-row\">"): Html.Raw(""))
// some code
#(count <= 3 ? Html.Raw("</div>") : Html.Raw(""))
#(count++)
}
By the way, returning IHtmlString is the way MVC recognizes html content and does not encode it. Even if it hasn't caused compiler errors, calling ToString() would destroy meaning of Html.Raw()
The accepted answer is correct, but I prefer:
#{int count = 0;}
#foreach (var item in Model.Resources)
{
#Html.Raw(count <= 3 ? "<div class=\"resource-row\">" : "")
// some code
#Html.Raw(count <= 3 ? "</div>" : "")
#(count++)
}
I hope this inspires someone, even though I'm late to the party.
You shouldn't be calling .ToString().
As the error message clearly states, you're writing a conditional in which one half is an IHtmlString and the other half is a string.
That doesn't make sense, since the compiler doesn't know what type the entire expression should be.
There is never a reason to call Html.Raw(...).ToString().
Html.Raw returns an HtmlString instance that wraps the original string.
The Razor page output knows not to escape HtmlString instances.
However, calling HtmlString.ToString() just returns the original string value again; it doesn't accomplish anything.
Related
I'm just inquisitive if this is possible. If so, please help me.
Everything is already set and valid like the:
-Model.info:
public class info{
public string information{get;set;}
}
-ViewBag.Infos:
ViewBag.Infos = new SelectList(new []{"Option1","Option2"});
-I am not finding or encountering an error.
So it goes like this:
#foreach(var nom in Model.info)
{
#Html.DropDownList("Infos",new{#Value = "nom.information"})
}
Is it possible to put the foreach value of nom into each dropdownlist's value?
First error is that you are iterating over Model.info that is an string (is an iteration over every char, the type of nom would be char).
By the other hand, you must define a DropDownList with the ViewBag elements, something like that:
#Html.DropDownList("info", ViewBag.info, null, Model.info)
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
I have an MVC Kendo Timepicker for that I am using. It works fine except that I can't format the time to Military time. After I add the formatting for Military time, once I select the time the validation doesn't pass and it tells me it must be a date. Is there a way to format the TimePickerFor to allow military time?
#using Kendo.Mvc.UI
#model DateTime?
#(Html.Kendo().TimePickerFor(m=>m)
.Value(#Model)
.Min("05:00")
.Max("00:00")
.Format("{0:HHmm}")
)
Update: This doesn't work with format being changed to .Format("HHmm")
Ok, so thanks to the Kendo people, I found the answer. The script may need some work depending on the situation. My TimePickerFor is in an Editor Template which sits in a grid with other timepickers and numeric text boxes. Only thing with this way of working is that once the script is fired, the numeric boxes used this script also to validate (hence the return $.isNumeric(input.val()) line. Hope this helps someone else out.
TimePickerFor Control:
#using Kendo.Mvc.UI
#model DateTime?
#(Html.Kendo().TimePickerFor(m=>m)
.Value(#Model)
.Format("HHmm")
.HtmlAttributes(new{data_format="HHmm"})
.ParseFormats(new[]{"HHmm"})
)
<script>
var originDate = kendo.ui.validator.rules.mvcdate;
kendo.ui.validator.rules.mvcdate = function(input) {
var format = input.attr("data-format");
if (input.val() == "") {
return kendo.parseDate("0000", format);
}
if (format) {
return kendo.parseDate(input.val(), format);
} else {
return $.isNumeric(input.val());
}
};
</script>
I think you have to remove the curly braces and make sure that is a valid format type. I also don't think the 0 is necessary.
Here's some formating documentation
http://docs.telerik.com/kendo-ui/getting-started/framework/globalization/dateformatting
#(Html.Kendo().TimePickerFor(m=>m)
.Value(#Model)
.Min("05:00")
.Max("00:00")
.Format("yyyy/MM/dd hh:mm tt")
)
Edit:
Is your max and min values correct? I don't see how that is logically correct.
I have converted my MVC3 application to MVC5, I had to change all views to razor. Having a challenge with a select list:
In ASPX view that works I am using the following:
<select id="Profession" name="Profession" style="width: 235px; background-color: #FFFFCC;">
<% List<string> allProfessions = ViewBag.AllProfessions;
string selectedProfession;
if (Model != null && !String.IsNullOrEmpty(Model.Profession))
selectedProfession = Model.Profession;
else
selectedProfession = allProfessions[0];
foreach (var aProfession in allProfessions)
{
string selectedTextMark = aProfession == selectedProfession ? " selected=\"selected\"" : String.Empty;
Response.Write(string.Format("<option value=\"{0}\" {1}>{2}</option>", aProfession, selectedTextMark, aProfession));
}%>
</select>
In Razor I am using:
<select id="Profession" name="Profession" style="width: 235px; background-color: #FFFFCC;">
#{List<string> allProfessions = ViewBag.AllProfessions;
string selectedProfession;}
#{if (Model != null && !String.IsNullOrEmpty(Model.Profession))
{selectedProfession = Model.Profession;}
else {selectedProfession = allProfessions[0];}
}
#foreach (var aProfession in allProfessions)
{
string selectedTextMark = aProfession == selectedProfession ?
"selected=\"selected\"" : String.Empty;
Response.Write(string.Format("<option value=\"{0}\" {1}>{2}</option>",
aProfession, selectedTextMark, aProfession));
}
</select>
The list shows up at the top of the page, I can't figure out where is the problem. Would appreciate your assistance.
Don't create your dropdown manually like that. Just use:
#Html.DropDownListFor(m => m.Profession, ViewBag.AllProfessions, new { style = "..." })
UPDATE
I tried your solution but got this error: Extension method cannot by dynamically dispatched
And, that's why I despise ViewBag. I apologize, as my answer was a little generic. Html.DropDownList requires the list of options parameter to be an IEnumerable<SelectListItem>. Since ViewBag is a dynamic, the types of its members cannot be ascertained, so you must cast explicitly:
(IEnumerable<SelectListItem>)ViewBag.AllProfessions
However, your AllProfessions is a simple array, so that cast won't work when the value gets inserted at run-time, but that can be easily fixed by casting it to a List<string> and then converting the items with a Select:
((List<string>)ViewBag.AllProfessions).Select(m => new SelectListItem { Value = m, Text = m })
There again, you see why dynamics are not that great, as that syntax is rather awful. The way you should be handling this type of stuff is to use your model or, preferably, view model to do what it should do: hold domain logic. Add a property to hold your list of profession choices:
public IEnumerable<SelectListItem> ProfessionChoices { get; set; }
And then, in your controller action, populate this list before rendering the view:
var model = new YourViewModel();
...
model.ProfessionChoices = repository.GetAllProfessions().Select(m => new SelectListItem { Value = m.Name, Text = m.Name });
return View(model);
repository.GetAllProfessions() is shorthand for whatever you're using as the source of your list of professions, and the Name property is shorthand for how you get at the text value of the profession: you'll need to change that appropriately to match your scenario.
Then in your view, you just need to do:
#Html.DropDownListFor(m => m.Profession, Model.ProfessionChoices)
Given that you don't have this infrastructure already set up, it may seem like a lot to do just for a drop down list, and that's a reasonable thing to think. However, working in this way will keep your view lean, make maintenance tons easier, and best of all, keep everything strongly-typed so that if there's an issue, you find out at compile-time instead of run-time.
I believe it's happening because of the Response.Write. Try this:
#Html.Raw(string.Format("<option value=\"{0}\" {1}>{2}</option>", aProfession,
selectedTextMark, aProfession))
when deciding on which ActionResult to return from a Controller Action I decided to use the ternary operators as opposed to the lengthier if-else. Here is my issue...
this code works
return
ModelState.IsValid ?
(ActionResult) RedirectToAction("Edit", new { id = id }) :
View(new EditViewModel(updatedCategory));
but this doesn't
return
ModelState.IsValid ?
RedirectToAction("Edit", new { id = id }) :
View(new EditViewModel(updatedCategory));
I would not have to do the explicit casting if using an if-else. Plus both RedirectToAction() and View() return an ActionResult derivative.
I like the terseness of this code but that casting doesn't seem right. Can anyone enlighten me?
Though I'm sure this is obvious, the EditViewModel is a view model for my Edit action and updatedCategory is an EF4 object. But I don't think this is relevant to the issue.
ok... I just realized what I was doing is unnecessary because regardless I am going back to the Edit action with the updatedCategory, so I don't need to make sure the Model is valid. I am still curious to know the answer to the question if anyone can help.
I believe it's because the arguments when using the ?: operator have to be convertable between themselves, e.g. in condition ? x : y you need to be able to convert x to y or y to x. Then the type of the result is the least specific of the two. So if x was an object and y a string then you can cast a string to an object and the result would be of type object.
In your example x is a RedirectToRouteResult and y is a ViewResult. You cannot convert a RedirectToRouteResult to a ViewResult or vice versa. You can convert them both to an ActionResult however, which is why if you cast to an ActionResult it works - the type of x is then an ActionResult,y can be converted to an ActionResult and the overall result is of type ActionResult.
Hope I've explained myself correctly there... Afraid I don't know the exact semantics of the ?: operator as I rarely use it myself...
The data types have to be exactly the same on the assignment variable and both return types here is the most simple example I can think of:
int originalValue = 10;
int? value = (originalValue != 10) ? null : originalValue;
//Which is very easily fixed with type casting as you have done
int? value = (originalValue != 10) ? null : (int?)originalValue;