I am trying to create a custom url which is within a loop so that through each loop the produced url is different. The code looks like this:
#foreach (var car in Model)
{
<div class="container">
#{string country = Html.DisplayFor(modelCar => car.Country).ToString()}
#{string mapUrl = "https://maps.googleapis.com/maps/api/staticmap?zoom=14&size=150x120&key=[insertkey]¢er="
+ country}
<img src=#mapUrl />
</div>
}
The problem is the line where I define mapUrlrenders an error. What is the problem with this code?
Thanks in advance.
I think you are simply missing the semi columns for the variables and quotes for the image src tag.
Also i am not sure why you are calling DisplayFor to get the country variable name! DisplayFor returns an MvcHtml string and is usually used to get the encoded html markup to render to browser. Unless you have some crazy overloading of that (why would you do that on DisplayFor ? Use a simply helper method), do not misuse the DisplayFor helper
This should work.
#foreach (var car in Model)
{
<div class="container">
#{ var country = car.Country; } // i assume you just need the Country
#{ var mapUrl = "https://maps.googleapis.com/maps/api/staticmap?zoom=14&size=150x120&key=[insertkey]¢er=" + country; }
<img src="#mapUrl" />
</div>
}
I'm trying to make a Price Range filter as you can see live here.
It's made in Umbraco 7.
I would like to hide a price range IF there is NO products in the range.
My code looks like this:
string selectedpriceRange = queryString.Get("priceRange");
<ul id="priceFilter" class="section sidebarList">
<li #(String.IsNullOrEmpty(selectedpriceRange) ? currentClass : "")>
All prices
</li>
#{ var priceRanges = new Dictionary<int, int>();
priceRanges.Add(0, 4999);
priceRanges.Add(5000, 9999);
priceRanges.Add(10000, 14999);
priceRanges.Add(15000, 24999);
priceRanges.Add(25000, 34999);
priceRanges.Add(35000, 44999);
priceRanges.Add(45000, 54999);
priceRanges.Add(55000, 95000);
}
#foreach (KeyValuePair<int, int> range in priceRanges)
{
<li>
<a href="#CurrentPage.Url#queryStringBuilder("priceRange", string.Format("{0}-{1}", range.Key, range.Value))">
#string.Format("{0} - {1}", range.Key, range.Value)
</a>
</li>
}
</ul>
I would like to think it's possible to add a .where or Count in the new Dictionary to see IF there is anything in that price range, but I'm not sure.
While binding dropdown in MVC, I always get this error: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country.
View
#Html.DropDownList("country", (IEnumerable<SelectListItem>)ViewBag.countrydrop,"Select country")
Controller
List<Companyregister> coun = new List<Companyregister>();
coun = ds.getcountry();
List<SelectListItem> item8 = new List<SelectListItem>();
foreach( var c in coun )
{
item8.Add(new SelectListItem
{
Text = c.country,
Value = c.countryid.ToString()
});
}
ViewBag.countrydrop = item8;
return View();
I don't know how to resolve it.
If you were using DropDownListFor like this:
#Html.DropDownListFor(m => m.SelectedItemId, Model.MySelectList)
where MySelectList in the model was a property of type SelectList, this error could be thrown if the property was null.
Avoid this by simply initializing it in constructor, like this:
public MyModel()
{
MySelectList = new SelectList(new List<string>()); // empty list of anything...
}
This often happens in POST actions. Make sure you assign something before re-rendering the view.
In your action change ViewBag.countrydrop = item8 to ViewBag.country = item8;and in View write like this:
#Html.DropDownList("country",
(IEnumerable<SelectListItem>)ViewBag.country,
"Select country")
Actually when you write
#Html.DropDownList("country",
(IEnumerable)ViewBag.country,
"Select country")
or
Html.DropDownList("country","Select Country)
it looks in for IEnumerable<SelectListItem> in ViewBag with key country, you can also use this overload in this case:
#Html.DropDownList("country","Select country") // it will look for ViewBag.country and populates dropdown
See Working DEMO Example
Note that a select list is posted as null, hence your error complains that the viewdata property cannot be found.
Always reinitialize your select list within a POST action.
For further explanation:
Persist SelectList in model on Post
try this
#Html.DropDownList("ddlcountry",(List<SelectListItem>)ViewBag.countrydrop,"Select country")
In Controller
ViewBag.countrydrop = ds.getcountry().Select(x => new SelectListItem { Text = x.country, Value = x.countryid.ToString() }).ToList();
Try This.
Controller:
List<CountryModel> countryList = db.countryTable.ToList();
ViewBag.Country = new SelectList(countryList, "Country", "CountryName");
I had a the same problem and I found the solution that I should put the code to retrieve the drop down list from database in the Edit Method. It worked for me.
Solution for the similar problem
In my case, the error occurred because I had not initialized the select list in the controller like this:
viewModel.MySelectList = new List<System.Web.Mvc.SelectListItem>();
As none of the existing answers made this clear to me, I post this. Perhaps it helps anybody.
your code is correct because in some cases it does not work, I also do not know where the error comes from but this can help you solve the problem, move the code in the head of the view like this:
index.cshtml:
#using expert.Models;
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
Manager db = new Manager();
ViewBag.FORM_PRESTATION = new SelectList(db.T_BDE_PRESTATION_PRES.OrderBy(p => p.PRES_INTITULE).Where(p => p.T_B_PRES_ID == null), "PRES_ID", "PRES_INTITULE");
}
<div class="form-group">
<label class = "w3-blue" style ="text-shadow:1px 1px 0 #444">Domaine:</label>
<div class="col-md-10">
#Html.DropDownList("FORM_PRESTATION", null, htmlAttributes: new { #class = "w3-select ", #required = "true" })
</div>
</div>
you can use this:
var list = new SelectList(countryList, "Id", "Name");
ViewBag.countries=list;
#Html.DropDownList("countries",ViewBag.countries as SelectList)
Replace "country" with "countrydrop" in your view like this...
#Html.DropDownList("countrydrop", (IEnumerable<SelectListItem>)ViewBag.countrydrop,"Select country")
Could be like for ASP.NET MVC Framework
#Html.DropDownList("country", ViewBag.countrydrop as List<SelectListItem>,"Select country")
or ASP.NET Core MVC
<select class="class" id="country"
asp-items="#(new SelectLits(ViewBag.countrydrop,"Value","Text"))">
You are facing this problem because when you are posting your forms so after reloading your dropdown is unable to find data in viewbag. So make sure that code you are using in get method while retrieving your data from db or from static list, copy paste that code into post verb as well..
Happy Coding :)
I'm using razor mvc and I want to build up an html string so that I can display it within a div, in php it would look like this:
$htmlstring = '';
foreach ($item as $items)
{
$htmlstring .= '<p>'.$item.'</p>';
}
<div>
<? echo $htmlstring; ?>
</div>
How would I do the equivalent in razor mvc?
You could just stick your code within a foreach loop on the Razor View
<div>
#foreach ( var item in Model.Items ){
<p>#item</p>
}
</div>
Assuming that the Model you pass in has a property called Items which is a Collection of some type.
I think you mean the ASP .NET MVC Razor View Engine.
#{
//this should come from controller
List<string> items = new List<string>() { "one", "two", "three" };
}
<div id="theDiv">
#foreach (var v in items)
{
//no need for building a string, sense we can just output the <p>xyz</p> inside the div
<p>#v</p>
}
</div>
I'm using MVC where I have a list of strings that I would like to point to a new page. I'm using Razor and am very new to MVC and cannot seem to find the answer to my question through google.
My list could contain of the following:
"hello"
"goodbye"
"seeya"
I know how to insert strings from the controller to the html page using ViewBag, and I would use the following actionlink if I had a fixed set of strings:
#Html.ActionLink("viewedName", "ChemicalClass", new { mystring = "hello" })
#Html.ActionLink("viewedName", "ChemicalClass", new { mystring = "goodbye" })
#Html.ActionLink("viewedName", "ChemicalClass", new { mystring = "seeya" })
As I understand it, this would generate 3 links that would redirect to the subpage "ChemicalClass", and it would contain the one of the 3 parameters, depending on the link that was clicked.
My quesiton is, how can I do the same, but have the ActionLinks created dynamically, since I won't know how many links are going to be created, nor the content of the strings. My goal is to show these links on the webpage in (preferabely) a list form, e.g.:
<ol>
<li>
hello
</li>
<li>
goodbye
</li>
<li>
seeya
</li>
</ol>
Where each element in the list is a link and not just a string.
Create a view model that stores a collection of links
Model
public class ViewModel
{
public IList<string> Links { get; set; }
}
populate that model in your controller
Controller
public ActionResult Index()
{
var model = new ViewModel
{
Links = new List<string>
{
"Hello",
"Goodbye",
"Seeya"
}
};
return View(model);
}
and finally your view
View
#model MvcApplication1.Models.ViewModel
<ol>
#foreach (var item in Model.Links)
{
<li>
#Html.ActionLink("viewedName", "ChemicalClass", new { mystring = item })
</li>
}
</ol>
Your class holds your collection of strings and razor loops over them to produce your links.
you can use something like this.
<ul>
#foreach (var x in Model)
{
<li>#x.myString </li>
}
</ul>
I have something like this in one of my Views:
#foreach (var item in Model.MyList)
{
<li>
#Html.ActionLink("Select", "ActionName", "Chemical", new {id = item.AdmNum}, new { #class = "label label-info"})
</li>
}