Comma-delimited and dash-delimited text fields in MVC 4 - asp.net-mvc

We have a Razor form in our web app. During a meeting with the clients, we learned that one of the fields in this form should accept input that is:
A list of comma-delimited numbers
including ranges of numbers expressed using dashes
For example, the end-users might enter 45,50-53,65 to represent the list of numbers 45, 50, 51, 52, 53, 65. I'm assuming that the textbox might contain arbitrary whitespace as well that should be ignored (so 45, 50-53, 65 would represent the same information).
How would I set up such a text box in MVC 4 using Razor? In particular,
How would I create the text box in my Razor view?
How would I represent the information in the text box in my model?
How would I data-bind the text box to the model?
How would I set up validation for the text box?

I would just create a normal textbox -- you're asking for a string of numbers
You could have the form value as a string, and then another property that is the parsed version of the string, int[].
Since it is a string, it can be posted as a string.
Use a regular expression for the validator.
For 2, you could do something like this in your model:
public string Numbers { get; set; }
public int[] ParsedNumbers
{
get
{
Func<int[], int[]> arrayToRange = (range) =>
{
if (range.Length == 1) return range;
int[] ret = new int[range[1] - range[0] + 1];
for (int i = 0; i < ret.Length; i++)
{
ret[i] = i + range[0];
}
return ret;
};
return this.Numbers
.Replace(" ", "")
.Split(',')
.SelectMany(n => arrayToRange(n.Split('-')
.Select(n2 => int.Parse(n2)).ToArray())).ToArray();
}
}
For 4, you could use this RegEx:
^(\d(\-\d)?(, ?)?)*$

Related

Dart Regex Matching

I want to check via regex in dart whether a line contains string such as ABS_D0 or ABS_D1, or ABS_D2 etc upto ABS_D40 and also ABS_DX.
var dcc1= "ABS_D0 4, 5, 158, b";
var dcc2 = "ABS_D1 3, 5, 157, b";
var dccEnd = "ABS_DX";
If line contains matching string then line is split via comma and stored in list.
example
ABS_D0 4, 5, 158, b should become list[0]=0,list[1]=4,list[2]=5,list[3]=158,list[4]=b
ABS_D1 3, 5, 157, b should become list[0]=1,list[1]=3,list[2]=5,list[3]=157,list[4]=b
You are not saying which tpe the list elements must have. The one containing "b" is clearly a string, but should 158 be a string or an integer?
I'll make it a string for now, you can always use int.parse if you want it as an integer.
final absRE = RegExp(r"ABS_D([1-4]?\d|X)\s*");
List<String> matchABS(String line) {
var match = absRE.firstMatch(line);
if (match == null) return null;
var result = [match[1]]
result.addAll(line.substring(match.end).split(",").map((s) => s.trim());
return result;
}
The regular expression matches "ABS_D" followed by either a number in the range 0..40 (well, it accepts up to 49 actually, but I assume that's not a problem) or "X". Then the code splits the rest of the line on commas.

How to convert decimal field value to currency in mvc

I have an few editorfor in my view like following
#Html.EditorFor(Model => Model.CashBalance)
Now when i enter any value in to that editorfor,the value should change to currency value in textbox change event
For ex:
123 should display as 123.00
14.35 should display as 14.35
I want to do this in generic way so that I don't need to change it every where as my project has many editorfor which takes inputs from user.
As I am using an EditorTemplate for all these textboxes,i want to handle here itself.
My EditorTemplate for this is decimal.cshtml and it looks like the foll
#model decimal?
#{
string value = (Model.HasValue == false || Model.Value == 0) ? "" : string.Format("{0:0.00}", Model.Value);
}
#Html.TextBox(
"",
value,
new { #class="amountRightAlign"}
)
Will there be any textchange event i can write here so that it affects where ever there is decimal datatype?
Thanks in advance?
Html helpers are server side code used to generate the html which is sent to the client. In order to interact with user changes in the browser, you need to use javascript to handle events.
In your case you don't need an EditorTemplate. Instead, just the overload of TextBoxFor() that accepts a format string
#Html.TextBoxFor(m => m.CashBalance, "{0:0.00}", new { #class="decimalnumber" })
Then in the view, or in a separate script file
$('.decimalnumber').change(function () {
var num = new Number($(this).val());
if (isNaN(num)) {
// Its not a valid number
return;
}
$(this).val(num.toFixed(2));
})

How can I SUM two different selections passed to model?

I am taking a prior question one step further (see this question), I am trying to figure out how to sum two (or more) selections the user makes with, for example, a radio button list. The selection the user makes is tied to an entity that contains a static currency value using if/else if statements.
These are the entities for price:
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "{0:c}")]
public decimal priceProcessingStandard = 0;
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "{0:c}")]
public decimal priceProcessingExpedited = 250;
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "{0:c}")]
public decimal priceSubmissionOnline = 0;
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "{0:c}")]
public decimal priceSubmissionManual = 200;
So, if I have two sets of if/else if statements such as:
#if (Model.ProcessingRadioButtons == Processing.Standard)
{
#Html.DisplayFor(m => m.priceProcessingStandard)
}
else if (Model.ProcessingRadioButtons == Processing.Expedited)
{
#Html.DisplayFor(m => m.priceProcessingExpedited)
}
...
#if (Model.SubmissionRadioButtons == Submission.Online)
{
#Html.DisplayFor(m => m.priceSubmissionOnline)
}
else if (Model.SubmissionRadioButtons == Submission.Manual)
{
#Html.DisplayFor(m => m.priceSubmissionManual)
}
and the user makes selections in the two separate radio button lists corresponding to Processing.Expedited and Submission.Manual, the code will respectively display $250.00 and $200.00.
I cannot, however, figure out how to sum those two to display $450.00. Bear in mind, I do not know the selections before hand, so doing priceProcessingExpedited + priceSubmissionManual in a function and then calling it will obviously not work. Also, I am doing about 10-15 of these but I only used two simple ones as an example of what I am trying to accomplish (so the fact that the other two choices are $0.00 doesn't mean anything because there are varying prices for other choices that I left out).
Any guidance?
UPDATE:
Based on suggestion in answer, I am doing this:
Model.calculated =
Model.priceSolution +
((Model.ProcessingRadioButtons == Processing.Standard) ?
Model.priceProcessingStandard :
(Model.ProcessingRadioButtons == Processing.Expedited) ?
Model.priceProcessingExpedited :
Model.priceProcessingUrgent);
Some notes:
priceSolution is a static value that I use as a base (it's the base value plus the user selections).
I am using calculated in the ViewModel and get; set;'ing it.
I left out the Namespace.ViewModels.MyData before Processing. for brevity.
I left out Submission for brevity as it's just a + then the same logic as in Processing.
You do know the selections before hand considering your #if (Model.SubmissionRadioButtions == Submission.Online) is a test against values currently held by the model - even if this is only after a POST.
As such, you should create a property in your view model that also performs these tests and sums the appropriate fields.
If you don't want this property displayed before the POST, make the property return a nullable type and wrap the view with #if(MySum.HasValue) { #Html.DisplayFor(m=>m.MySum) }

Advanced ASP.NET WebGrid - Dynamic Columns and Rows

I'm trying to create a WebGrid which has to be very dynamic. The columns are defined in a list, which I've done like so:
#{
List<WebGridColumn> columns = new List<WebGridColumn>();
foreach (var column in Model.Columns)
{
columns.Add(new WebGridColumn() { ColumnName = column.Name, Header = column.Name });
}
}
#grid.GetHtml(
columns: columns)
All well and good, but the problem I have is with the rows. I'll try and explain...
For this question let's say we have two columns for Name and Address.
I have a collection of row objects, lets say SearchResult objects. A SearchResult contains a Dictionary of any number of attributes, such as Name, Address, Phone, Height, Bra Size, or anything (think of the EAV pattern). I need to access the attributes based on Column Name.
I figured I could do this using format, but I can't seem to figure it out. I want something like this:
columns.Add(new WebGridColumn() { ColumnName = column.Name, Header =
column.Header, Format = #<text>#item.Attributes[column.Name]</text> });
This sort of works but despite creating the format for the separate columns, the rows get populated with only the last column's format. i.e.:
Name Address
1 Main Street 1 Main Street
45 Paradise Av 45 Paradise Av
etc
I think it should work if you leave out the "ColumnName" (superfluous anyway), and also make the dynamic expression a bit more explicit:
columns.Add(
new WebGridColumn() {
Header = column.Header,
Format = (item) => #Html.Raw("<text>" + #item.Attributes[column.Name] + "</text>")
}
);
This issue is related to reference variables. You need to have the Format property in terms of the other properties of the WebGridColumn. This is how I would do it:
#{
List<WebGridColumn> columns = new List<WebGridColumn>();
foreach (var column in Model.Columns)
{
var col = new WebGridColumn();
col.Header = column.Name;
col.Format = (item) => #Html.Raw("<text>" + #item.Attributes[col.Header] + "</text>");
columns.Add(col);
}
}

How do I get Choice Values from a Document library's Choice column in code

I am fairly new to SharePoint development and as you may all know that it is very basic for one to know how to access fields in a choice column...
My problem:
I want to access the values of the Check Boxes from a Choice Column.
For Example:
I have a document library called Libe, this document library has a custom column with type Choice and has 4 checkboxes with the values:
Category 1
Category 2
Category 3
Category 4
How do I get the values like literally the text values of what is in the Check Box List: "Category 1", "Category 2" ... "Category 4".
Any ideas?
I can access the column fine and get the selected values, I just do not know how to get the values the user can choose from.
Answer
SPFieldMultiChoice Fld = (SPFieldMultiChoice)list.Fields["Column"];
List<string> fieldList = new List<string>();
foreach (string str in Fld.Choices)
{
fieldList.Add(str);
}
Above is the answer, I can't answer my own question until I have a 100 rep.
using (SPSite site = new SPSite("http://servername/"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["ListName"];
string values = list["yourColumn"] as string;
string[] choices = null;
if (values != null)
{
choices = values.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
}
}
}
You can try this code for getting choice field value from document library.

Resources