Reputation: 454
I have some strings and I would like to get the Index Number out from them.
Here is the example.
var x = "FundList[10].Amount";
var y = "FundList[11].Amount";
var z = "FundList[15].Amount";
I simply want to get the 10,11,15 and put them into an array of Int.
Currently, I am using a stupid way, which is to replace "FundList[", "]" and ".Amout" with "".
I am wondering if there is a better way to do so.
Here are some clarifications. Here is my code.
This is my part of my PartialView.
@{
var txtIndexName = "FundList[" + Model.Index + "].Index";
var txtAmountName = "FundList[" + Model.Index + "].Amount";
var dropFiscalYearName = "FundList[" + Model.Index + "].FiscalYear";
}
Amount: <input type="text" name="@txtAmountName" id="@txtAmountName" />
Here is the JavaScript to call the PartialView. Each time when user click on a anchor link, the PartialView will be called.
function LoadContractOptionFundingPlanBlockByIndexNumber(indexNumber) {
$.ajax({
type: "POST",
url: "/Json/LoadContractOptionFundingPlanPartialView",
data: JSON.stringify({ index: indexNumber }),
contentType: "application/json; charset=utf-8"
}).success(function (result) {
$("#ContractOptionFundingPlanBlock").append(result);
});
}
function GenerateOptionFundingPlanBlock() {
$("#lnkAddFundingBlock").click(function () {
LoadContractOptionFundingPlanBlockByIndexNumber(currentIndexNumber);
currentIndexNumber++;
});
}
$(document).ready(function () {
GenerateOptionFundingPlanBlock();
});
var currentIndexNumber = 10;
Here is my View:
<form action="#" method="post" name="formCreateContracOption" id="formCreateContracOption">
@Html.AntiForgeryToken()
@Html.LabelForRequired(x=>x.ThisContractOption.OptionName)
@Html.ValidationMessageFor(x=>x.ThisContractOption.OptionName)
@Html.TextBoxFor(x=>x.ThisContractOption.OptionName) <br/><br/>
Period of Performance
@Html.TextBoxFor(x=>x.ThisContractOption.OptionStartDate)
@Html.TextBoxFor(x=>x.ThisContractOption.OptionEndDate) <br /><br />
<a id="lnkAddFundingBlock" href="#">Add Funding Plan</a> <br/><br/>
<div id="ContractOptionFundingPlanBlock"></div>
<input type="submit" id="btnCreateContractOption" name="btnCreateContractOption" value="Submit" />
</form>
After all, when user clicks on the Submit button, the whole thing will be posted to the controller.
Here is my Controller.
[HttpPost]
public ActionResult CreateContractOption(int contractId, ContractOptionCreateEditViewModel viewModel, FormCollection form)
{
var fundList = new List<OptionFundingPlanObject>();
var allOptionAmountKeyList = form.AllKeys.Where(x => x.Contains("FundList") && x.Contains("Index")).ToList();
var indexNumberList = new List<int>();
foreach(var thisKey in allOptionAmountKeyList)
{
var convertedIndex = Convert.ToInt32(Regex.Match(thisKey, @"\d+").Value);
indexNumberList.Add(convertedIndex);
}
return View();
}
The reason I am asking is because it is not simply a How to Post a List to the controller question.
When the List starts with a ZERO index, and every other index is in a sequence, it is pretty easy to handle.
In my case, user may generate a new Option, by calling my Partial View. User will have the ability to remove the generated option, and create a new one. The index then changed. In this case, I have to find another way to solve the problem.
Upvotes: 0
Views: 130
Reputation: 11228
If you prefer LINQ syntax to Regex:
var x = "FundList[10].Amount";
int n = Int32.Parse(new string(x.Where(c => Char.IsDigit(c)).ToArray())); //10
Upvotes: 0
Reputation: 20014
Maybe something like: Online Demo
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string text = "FundList[15].Amount";
var result = Convert.ToInt32(Regex.Replace(text, @"[^\d]+",""));
Console.WriteLine("Result is = {0}", result);
}
}
Upvotes: 0
Reputation: 175768
As its fixed as FundList
simply:
int i = int.Parse(x.Substring(9, x.IndexOf(']') - 9));
Upvotes: 0
Reputation: 8782
If you are always going to have the strings in the form you provided you can split it on the brackets and get the item from the returned string array:
var x = "FundList[10].Amount";
var num = x.Split('[', ']')[1];
int res = Convert.ToInt32(num);
Upvotes: 1
Reputation: 23786
var x = "FundList[10].Amount";
int xIndex = Convert.ToInt32(Regex.Match(x,@"\d+").Value); //10
This is a werid question though. What are you doing? :)
Upvotes: 5