How to do number formatting in mvc3 view - asp.net-mvc-3

I want to get the output TotalAmount ( for example: 1000000000 as 1,000,000,000 ) but my code throws this error:
[ Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions. ].
Please give me solutions on my below context.
#Html.DisplayFor(modelItem => item.TotalAmount.ToString("#,##0.00"))

Model
[DisplayFormat(DataFormatString = "{0:0,0}")]
public virtual Decimal? TotalAmount{ get; set; }
View
Html.EditorFor(model => model.TotalAmount)

You could try this one. ( it would handle even the nullable columns)
#Html.Raw(string.Format("{0:#,#.00}", Model.TotalAmount))

Related

Net Core - .Include() results in loop causing Visual Studio debug to crash

My database has a one-to-many relation between "UsageRecord" and "Dimension"
This is modelled as follows (using a Database-First approach):
public partial class Dimension
{
...
public virtual ICollection<UsageRecord> UsageRecord { get; set; }
}
Usage Record class:
public partial class UsageRecord
{
public long Id { get; set; }
...
public long DimensionId { get; set; }
public virtual Dimension Dimension { get; set; }
}
So, if i query the list of UsageRecords (EagerLoading):
_context.Set<UsageRecord>.Where(x => x.ProductId == productId).ToList()
i get a list of UsageRecord objects I can navigate through during debug:
Please notice that the Dimension object is null, and this is correct since i haven't included it in the query.
Now, If i try to include it, the application crashes:
_context.Set<UsageRecord>.Where(x => x.ProductId == productId).Include(p => p.Dimension).ToList();
Postman exits with a 502 error, and the VS Debug first shows a list of question marks "?" before crashing.
I think this is due to the fact that by Including the Dimension object, this loops through the list of UsageRecords attached and then the Dimension again and again.
How can I avoid it?
In order to retrieve your result from LINQ query you can solve your issue in these ways:
Configure your serializer to ignore loops
Create a view model for your controller's action
Use anonymous type from Select result in your controller's action

Removing comma from IntegerTextBoxFor

I have a question about the IntegerTextBoxFor from Telerik Extensions for MVC. I'm currently trying to remove the use of commas from it. Currently here is what I have.
Editor Template called Int32.cshtml
#model System.Int32
#using Telerik.Web.Mvc.UI
#Html.Telerik().IntegerTextBoxFor(model => model)
Model
[NopResourceDisplayName("Admin.ReturnRequest.List.SearchOrderId")]
public int SearchOrderId { get; set; }
I have tried adding [DisplayFormat(DataFormatString="{0:g}")] to the model but it has done nothing. I also tried using 0:#####, 0:00000, and 0:n.
You can configure the group separator with calling the NumberGroupSeparator method on the IntegerTextBoxFor(model => model).
So if you don't need the separator you can set it to the empty string:
#Html.Telerik().IntegerTextBoxFor(model => model).NumberGroupSeparator("")
Telerik don't have this "NumberGroupSeparator" method on Kendo UI.
#(Html.Kendo().IntegerTextBoxFor(model => model)

How to making Display Template Work Correctly

I am trying to learn MVC. I had a very simple requirement that I wanted to insert commas in number displayed in a table. This is what I have.
Model
public partial class PACKAGE
{
public string PACKAGEID { get; set; }
[UIHint("withcommas")]
public Nullable<long> FILESIZE { get; set; }
}
Views\Shared\DisplayTemplates\withcommas.cshtml
#Model withcommas
#{
<span>[#Model.ToString("#,##0")]</span>
}
I did want to add the sqare brackets around it.
Views\Home\Packages.cshtml
#Html.DisplayFor(modelItem => item.FILESIZE)
What I am getting on the display is "2287097 withcommas [2,287,097];"
I do not understand why the original number as well as name of the hint is showing up in addition to the formatted number. I do not understand why there is an extra semicolon at the end.

Required field not present on all pages leading to problems

I have a ‘Create’ page in my MVC3 application that has 4 input fields that are all required. I also have an ‘Edit’ page in which 3 of these 4 fields can be edited. I do not want to display the 4th field and want to maintain it at its initial value (the field is the date that the entry was created ).
I mark the 4th field as [Required] in the model then this causes the model to be declared as invalid in post action method of the Edit field. If I omit the [Required] annotation then someone can create a user with a null value for this 4th field.
How can I get around this problem?
Model Code:
[Required]
[DisplayName("User Name")]
public string UserName { get; set; }
[Required]
public string Role { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayName("Insert Date")]
public DateTime? InsertDate { get; set; }
[Required]
[DisplayName("Active")]
public bool ActiveInd { get; set; }
Controller Code:
public ActionResult Edit(int id, ZUserRoleModel mod)
{
if (ModelState.IsValid)
{
// code removed
return RedirectToAction("Index");
}
return View(mod);
}
You can make that field as hidden in edit mode.
#Html.HiddenFor(x => x.EntryDate)
Not sure if you still need an answer for this, but what you need to do in order for the
#Html.HiddenFor(x => x.EntryDate )
to work, is pass an existing model into view. So let's assume that your action for getting the user data looks like this. ( You did not supply it, so I am not sure if this is right )
Public ActionResult GetUser(int UserID)
{
ZUserRoleModel model = new ZUserRoleModel(UserID);
// Maybe this could go to your database and gather user
// It would populate the correct data into a model object
return View("Edit", model);
}
With combination of the hidden field, your view will be populated with the existing user information, and the hidden field will be populated with data, and it will be passed to your edit action.
NOTE: I wrote this without any kind of testing, but it should still work, or at the very least, I hope it points you in the right direction if you still need assistance.
You can use fluentvalidation: http://fluentvalidation.codeplex.com/
Have a rule that's something like
RuleFor(user => user.field4).NotEmpty().When(ViewContext.Controller.ValueProvider.GetValue("action").RawValue <> "edit")

Remove default value for non nullable properties when using EditFor [asp.net mvc 3]

How can I remove the default value that is added by default to the textboxes of non nullable properties when using the EditFor helper? I don't want that behavior
EDIT
Sorry I didn't give enough information.
For example if you use Html.EditorFor with a property that is DateTime it will set the textbox value to 1/1/0001 automatically. If you use "DateTime?"(nullable), it won't, it just leaves the textbox empty.
You can use UIHint to do it.
Create a file called ShortDate.cshtml in EditorTemplates
#model DateTime
#{ var value = Model == default(DateTime) ? null : Model.ToShortDateString(); }
#Html.TextBox(string.Empty, value)
Decorate your property with the UIHintAttribute referencing our EditorTemplate. Consider my Order class.
public class Order {
[UIHint("ShortDate")]
public DateTime Date { get; set; }
}
When you use
#Html.EditorFor(x => x.Date)
it should avoid the default value of DateTime
caveat: I just did simple tests, so please take a deep look into it.
hope it helps you
I had to do something like this for my own needs. I used this:
#model DateTime?
#Html.TextBox("", (Model.Value != default(DateTime) ? Model.Value.ToShortDateString() : string.Empty))
and it worked pretty nicely for my DateTime values. Ones that didn't have the default value are blank and the ones that have some other DateTime value show the ShortDateString representation of the object.

Resources