I have this code :
0#Model.Work.Phone
When I use phone like 0#Model.Work.Phone, the # sign is not highlighted. And this looks like this in browser : 0#Model.Work.Phone . I mean the code is displayed instead of the phone number.
When I put a space like this :
0 #Model.Work.Phone
The # sign is higlighted but I want 0 and # to be next to each other. How can I achieve this? Thanks.
On Razor (at least on 2.0 or up) you can use an explicit expression:
0#(Model.Work.Phone)
As an alternative you can use the direct string.format call as offered by Gypsy Spellweaver
Another alternative is using an Razor delegate:
#{
Func<dynamic, object> phoneformat = (item) =>
{
// if we have a string
if (item is String && !String.IsNullOrEmpty(item))
{
// check if the first is not a 0
if (item[0] != '0')
{
// add it
item = String.Format("0{0}", item);
}
}
else if(item is Int32)
{
/// ints never have leading 0, so add it
item = String.Format("0{0}", item);
}
return item;
};
}
0#(Model.Work.Phone) <br/>
0#(Model.Work.PhoneInt)
#phoneformat(Model.Work.Phone) <br/>
#phoneformat(Model.Work.PhoneInt)
Here is the Model I used:
public class Work
{
public string Phone { get; set; }
public int PhoneInt { get; set; }
}
And the Controller that fills it:
public ActionResult Index()
{
var model = new MyModel();
model.Work = new Work {Phone = "612345678", PhoneInt = 612345678};
return View(model);
}
The rendered html content looks like this:
0612345678 <br/>
0612345678
0612345678 <br/>
0612345678
Related
i have transform a php/js code to js/c#, but i stuck for update the new value.
The php code is :
`if (isset($_POST['update'])) {
foreach($_POST['positions'] as $position) {
$index = $position[0];
$newPosition = $position[1];
$conn->query("UPDATE country SET position = '$newPosition' WHERE id='$index'");
}
exit('success');
}`
My "empty" c# code
[HttpPost]
public ActionResult Index (userTable index)
{
picturesEntities MyDb = new picturesEntities();
homeViewModel HVM = new homeViewModel();
HVM.userTables = MyDb.userTables.ToList();
if (Request["update"] != null)
{
foreach (Request["positions"])
{
MyDb.SaveChanges();
}
return View(HVM);
}
}
If someone could help me for it that would be great, i'm stuck on it for days and i didn't find a workning solution yet.
Thanks to everyone who read my message.
Most ASP.NET will bind a custom class which will be compatible to your request.
public class UserPositionsRequest
{
public bool Update { get; set; }
// For orderly, this actually be a list of a custom class
public List<int[]> Positions { get; set; }
}
This by any means is not a complete and working solution, the following code was never been tested and can be consider as pseudo-like code.
Also, the .Id and .Position should be the same sensitivity as in Db.
// Binding our UserPositionsRequest class
public void Index(UserPositionsRequest request) {
// Checking if we should update, if you will change the request to boolean type: "true"
// ..on the client side, then you could actually change the condition to be: if (request.Update)
if (request.Update == 1) {
// Creating database connection using (I assume) EntityFramework
using (var picturesEntities = new picturesEntities()) {
// Building a dictionary for fast lookup. Key, Value as the 0, 1 arg respectfully
var usersDataToUpdate = request.Positions.ToDictionary(p => p[0], p => p[1]);
// Finding the entries that needs to be updated
var usersEntitiesToUpdate = picturesEntities.userTables.Where(cntry => usersDataToUpdate.ContainsKey(cntry.Id));
// Iterating over the entities
foreach (var userEntity in usersEntitiesToUpdate) {
// Updating their position.
userEntity.Position = usersDataToUpdate[userEntity.Id];
}
picturesEntities.SaveChanges();
}
}
// Probably you wanted to return something here, but it's probably an ajax and you can skip that.
}
I'm newby to MVC and I want to have different body class for each view.
My header is a partial view and #RenderSection does not work for it.
_Layout.cshtml:
#{
Html.RenderAction("GetHeader", "Main");
}
#RenderBody()
#{
Html.RenderAction("GetFooter", "Main");
}
_HeaderLayout.cshtml:
//...
<body class=" here must be specified class different for each view">
//...
MainController:
public class MainController : Controller
{
public ActionResult GetHeader()
{
return PartialView("~/Views/Shared/_HeaderLayout.cshtml");
}
public ActionResult GetFooter()
{
return PartialView("~/Views/Shared/_FooterLayout.cshtml");
}
}
Any idea please?
I would do it in two ways:
Create a base ViewModel class for all the view models used in your app and add a property for the BodyClass, then implement it in the Partial View.
Add a property in the ViewBag dictionary before returning the partial view.
Examples:
1. Base class
public class BaseViewModel
{
public string BodyClass {get; set;}
}
Usage:
Base Class:
in partial view:
#model BaseViewModel
///...
<body class="#Model.BodyClass">
in controller:
public ActionResult GetHeader()
{
var vm = new BaseViewModel { BodyClass= "test-class" };
return PartialView("~/Views/Shared/_HeaderLayout.cshtml", vm);
}
In ViewBag:
public ActionResult GetHeader()
{
ViewBag[SomeConstantStringValue] = "test-class";
return PartialView("~/Views/Shared/_HeaderLayout.cshtml");
}
in partial view:
<body class="#ViewBag[SomeConstantStringValue]">
Remember that you always have to specify that ViewBag value, otherwise you'll get an error.
Mihail Stancescu answer is probably best, but if you don't want a view model for each controller method, you could make use of a helper function instead. Either way though, your're going to probably have to make your own method that decides which class to return (see BodyClassForTabAndMethod() below).
Create a Helper class (if you don't have a suitable one already):
public static class Helper
{
public static string BodyClassForTabAndMethod()
{
string[] selectedTabAndMethod = GetSelectedTabAndMethod();
string bodyClass = "";
// Change the below switch statements based upon the controller/method name.
switch (selectedTabAndMethod[0])
{
case "home":
switch (selectedTabAndMethod[1])
{
case "index":
return "IndexClass";
case "about":
return "AboutClass";
case "contact":
return "ContactClass";
}
break;
case "account":
switch (selectedTabAndMethod[1])
{
case "login":
return "LoginClass";
case "verifycode":
return "VerifyCodeClass";
}
break;
}
return bodyClass;
}
public static string[] GetSelectedTabAndMethod()
{
string[] selectedTabAndMethod = new string[2]; // Create array and set default values.
selectedTabAndMethod[0] = "home";
selectedTabAndMethod[1] = "index";
if (HttpContext.Current.Request.Url.LocalPath.Length > 1)
{
// Get the selected tab and method (without the query string).
string tabAndMethod = HttpContext.Current.Request.Url.LocalPath.ToLower();
// Remove the leading/trailing "/" if found.
tabAndMethod = ((tabAndMethod.Substring(0, 1) == "/") ? tabAndMethod.Substring(1) : tabAndMethod);
tabAndMethod = ((Right(tabAndMethod, 1) == "/") ? tabAndMethod.Substring(0, tabAndMethod.Length - 1) : tabAndMethod);
// Convert into an array.
if (tabAndMethod.Count(s => s == '/') == 1)
{
string[] split = tabAndMethod.Split('/');
selectedTabAndMethod[0] = split[0];
selectedTabAndMethod[1] = split[1];
}
}
return selectedTabAndMethod;
}
public static string Right(string value, int length)
{
if (string.IsNullOrEmpty(value)) return string.Empty;
return ((value.Length <= length) ? value : value.Substring(value.Length - length));
}
}
And then in your view:
<body class="#Helper.BodyClassForTabAndMethod()">
I reached to a solution for my own question, very simply:
In Global.asax: //or any other class which loading at start
public static class WrrcGlobalVariables
{
//any other global variables...
public static string BodyClass { get; set; }
}
In any Controller and before returning view/partial view:
public ActionResult Index()
{
//some codes...
WrrcGlobalVariables.BodyClass = "HomePage";
return View();
}
and in _HeaderLayout.cshtml:
<body class="#WrrcGlobalVariables.BodyClass">
Both the approaches given by Mihail Stancescu are correct, however there is one more way to have a default value for it and custom value only when required. Also you should use RenderPartial as well for your case instead of RenderAction if all you're doing is rendering the partial without any extra logic which requires a child controller.
In _Layout.cshtml
#Html.Partial("_HeaderLayout")
#RenderBody()
#Html.Partial("_FooterLayout")
In _HeaderLayout.cshtml
<body class="#ViewBag[SomeConstantStringValue]">
In _ViewStart.cshtml
#{
ViewBag[SomeConstantStringValue] = ViewBag[SomeConstantStringValue] ?? "default-class";
}
Then anywhere in any view or controller set this ViewBag value, this way you'll ensure a guaranteed default value to prevent null reference exceptions
I'm currently trying to implement a Dropdown List with what I would assume is hardcoded values. Basically what I want is to have a Dropdown List with a choice of three possible values.
I have a total of 4 controllers and views that will be using this dropdown. I've seen a lot of examples for MVC2 and MVC3 where people have hard coded their dropdowns in their views, and I personally don't prefer to go with a quick and "dirty" fix such as that.
I have a model containing the following.
public class Status
{
public int id { get; set; }
public string status { get; set; }
public Status(int statusId, string statusName)
{
id = statusId;
status = statusName;
}
}
The status should be able to have any of the 3 possible values:
Active
Inactive
Processing
I thought of creating the status' using this method I currently have in my status class:
public static List<Status> getAllStatus()
{
List<Status> states = new List<Status>();
states.Add(new Status(1, "Active"));
states.Add(new Status(2, "Inactive"));
states.Add(new Status(3, "Processing"));
return states;
}
I haven't been able to figure out how to use this model inside my Controllers alongside with how to pass it along to my views and was hoping someone in here would known how to do that?
EDIT1:
I guess I forgot to mention that I will be storing the selected value as a string in my database and that I am using a view which doesn't have the model of my status class, but rather the model of object which I will be storing in my database (which might be the case of a vehicle object).
EDIT2:
I have a model called Customer, which has some of the following values:
public int CustomerID { get; set }
public string Email { get; set }
public string Phone { get; set }
public Status Status { get; set; }
In my DB for my Customer model I have a string in which I wan to store the selected Status.
So basically I wan't to change the following to a dropdown with 3 options, Inactive, Active and Processing.
However I don't want to code this in my view as I will be needing it in 8 different views and copy pasting that is not very sleek code.
#Html.DropDownListFor(m => m.status_id, new SelectList(getAllStatus(), "id", "status"))
It doesn't make much sense to save it as a string within your database as it sounds more like something static. So u should consider an Enum. To me more precise look to my previous answer and add those Model properties to a ViewModel.
public class CustomerViewModel () {
public int SelectedStatusId { get; set; }
[DisplayName("Status")]
public IEnumerable<SelectListItem> StatusItems
{
get
{
yield return new SelectListItem { Value = "", Text = "- Select a status -" };
StatusTypeEnum[] values = (StatusTypeEnum[])Enum.GetValues(typeof(StatusTypeEnum));
foreach (StatusTypeEnum item in values)
{
if (item != StatusTypeEnum.Unknown)
{
yield return new SelectListItem { Value = ((int)item).ToString(), Text = item.GetDescription() };
}
}
}
}
}
Pass this into your View through your controller:
public class CustomerCOntroller(){
public ActionResult Index(){
CustomerViewModel viewModel = new CustomerViewModel();
return View(viewModel);
}
}
And you are done. If u are more working with a list which u need to build up add it to your viewModel object.
Greetings,
S..
To start you have a lot of vague questions. Be more specific if you can. If you don't know how MVC works that well I would recomment to follow some tutorials on it.
Model.cs (A ViewModel is preferred). You Should create a ViewModel which you passes to the View. Below is an example how to get a list of items.
public int SelectedStatusId { get; set; }
[DisplayName("Status")]
public IEnumerable<SelectListItem> StatusItems
{
get
{
yield return new SelectListItem { Value = "", Text = "- Select a status -" };
StatusTypeEnum[] values = (StatusTypeEnum[])Enum.GetValues(typeof(StatusTypeEnum));
foreach (StatusTypeEnum item in values)
{
if (item != StatusTypeEnum.Unknown)
{
yield return new SelectListItem { Value = ((int)item).ToString(), Text = item.GetDescription() };
}
}
}
}
StatusTypeEnum.cs
public enum StatusTypeEnum()
{
[Description("Active")] // For correct naming
Active,
Inactive,
Processing
}
View.cshtml
#Html.DropDownListFor(x => Model.SelectedStatusId, Model.StatusItems)
EnumAttribute.cs (To read the Annotation Descriptions. And don't try to understand this. It's just magic. It gets the DataAnnotation of the enum types by reflection.)
public static class EnumAttribute
{
public static string GetDescription<TEnum>(this TEnum value)
{
var fi = value.GetType().GetField(value.ToString());
if (fi != null)
{
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
}
return value.ToString();
}
}
You could declare States as public propery in your class and use this to access it in your views:
<ComboBox Grid.Column="1" Grid.Row="0" Margin="5"
VerticalAlignment="Center" ItemsSource="{Binding States}"
IsTabStop="False"}"/>
I've been struggling to research an answer to this question as I cannot come up with the correct search terms.
Basically I have 2 IEnumerable<T>'s in my controller, below is the code for the attempt I made.
Controller:
IEnumerable<Room> allRooms = RoomHelper.FindAllRooms();
foreach (var room in allRooms)
{
IEnumerable<Bunk> associatedBunks = RoomHelper.FindAssociatedBunksByRoom(room);
if (associatedBunks.Count() > 0)
{
ViewData["Room_"+room.RoomId] = associatedBunks;
}
}
And I'm trying to send them to the view in a way that I can do two foreach loops that will cycle through one set of data (in this case the Room objects and will then using the Room.RoomId key cycle through another IEnumerable which contains the associated data.
My view looks like this but is showing parse errors:
#foreach (var room in ViewBag.Rooms)
{
<h2>#room.RoomName</h2>
#if (ViewData["Room_" + room.RoomId].Count() > 0)
{
<ol>
#foreach (var bunk in ViewData["Room_" + room.RoomId])
{
<li>#bunk.BunkId</li>
}
</ol>
}
}
The end result I'm looking for in the HTML is something like:
<h2>Room 1</h2>
<ol>
<li>Bunk 1</li>
<li>Bunk 2</li>
</ol>
<h2>Room 2</h2>
<ol>
<li>Bunk 3</li>
<li>Bunk 4</li>
</ol>
What is the best practice in ASP.NET MVC 4 with EF5 to achieve this kind of result when passing "multidimensional" (is this multidimensional?) data?
Don't rely on ViewData. Store the data that you want to pass on to your view in a proper ViewModel:
public class RoomViewModel
{
List<Room> Rooms { get; set;}
...
}
Store your data in one of those.
Your Controller method then returns an instance of it:
public RoomViewModel GetRooms(int someParameter)
{
RoomViewModel result = new RoomViewModel();
result.Rooms = RoomHelper.Something(someParameter);
...
return result;
}
Your View declares its model on top:
#model MyApplication.ViewModels.RoomViewModel
and hence you use it in your View.
<h2>#Model.Rooms.Count rooms found</h2>
etc.
Use a code block in your view instead of adding an '#' in front of each C# statement:
#{
foreach (var room in ViewBag.Rooms)
{
#Html.Raw("<h2>" + room.RoomName + "</h2>");
if (ViewData["Room_" + room.RoomId].Count() > 0)
{
#Html.Raw("<ol>");
foreach (var bunk in ViewData["Room_" + room.RoomId])
{
#Html.Raw("<li>" + bunk.BunkId + "</li>");
}
#Html.Raw("</ol>");
}
}
}
You should avoid the use of #HtmlRaw("") as far as possible as it has a XSS vulnerability. But this should put you on the right track.
As per description given by you it seems that Bunk is associated with rooms. If that's the case then Bunk may have some id for pointing to room it belongs. Now you can create a ViewModel like this
public class BunkViewModel:Bunk
{
public BunkViewModel()
{
Mapper.CreateMap<Bunk,BunkViewModel>();
}
//I'm assuming that you already have some id in bunk to point to room it belongs.
//But writing it here to make it clear
public int RoomId { get; set; }
public string RoomName { get; set; }
//Use AutoMapper to Map
public static BunkViewModel Map(Bunk source)
{
return Mapper.Map<Bunk,BunkViewModel>(source);
}
}
Now in your controller
public ActionResult ActionName()
{
var result = new List<BunkViewModel>();
var rooms = RoomHelper.FindAllRooms();
var bunks = BunkHelper.GetAllBunks();
foreach(var bunk in bunks)
{
var bunkViewModel = BunkViewModel.Map(bunk);
var room = rooms.FirstorDefault(r=>room.RoomId == bunk.RoomId);
bunkViewModel.RoomId = room.RoomId; //No need to set if you already have this id in bunk
bunkViewModel.RoomName = room.RoomName;
result.Add(bunkViewModel);
}
return View(result.);
}
Now in your view you can do like this
#model List<MyApplication.ViewModels.RoomViewModel>
#foreach(var bunk in Model)
{
//Print it here as you want..
}
My models:
public class htmlDump {
public string html { get; set; }
}
public string getSquares() {
var sq = (from s in n.squares
where s.active == true
orderby s.date_created descending
select s.html).First();
return sq;
}
My controller:
public ActionResult index() {
intranetGS.htmlDump sq = new intranetGS.htmlDump {
html = g.getSquares()
};
return View(sq);
}
My View:
#Html.DisplayFor(model => model.html)
All I want is for the html being passed to the view to be rendered as html and not as text. Surely there's something different I can use in the view (instead of .DisplayFor) that will work. Any suggestions?
Thanks very much!
#Html.Raw(Model.html)
NOTE: if this data can be input by the user - make sure it's sanitized.