Access Array declared in C# Controller in Razor - c#

I have a 2D Array declared in my MVC Controller, and I need to access this via Razor so I can loop through each value.
I create a session and set it as the array, but I can't figure out how to access the array through razor.
Controller:
string[,] Things = new string[,] {
{ "thing1", "pie" },
{ "thing1", "cake" },
{ "thing1", "potato" }
};
public void GetThings()
{
Session["Things"] = Things;
}
public ActionResult Index()
{
GetThings();
return View();
}
Razor:
#{
for (int i = 0; i < Session["Things"].GetLength(0); i++)
{
#i
}
}
I get the error "'object' does not contain a definition for Getlength, the only suggested actions are .Equals, .GetHashCode, .GetType, and .ToString.
The above c# in the razor works if I declare the array within the razor, replacing "Session..." with the array variable name.
I can't read any values from the array session to display on the HTML front end, doing #Session["Things"] displays System.String[,] in browser (but then this is the same as if I tried to call the array declared in razor), #Session["Things"][1,1] gives browser error
Cannot apply indexing with [] to an expression of type 'object'

Cast to array:
((string[,])Session["Things"]).GetLength(0)

Related

Is it possible to bind list of strings to Action Result Include property

In in the snippet below
public async Task<ActionResult> CreateAsync([Bind(Include = DataRequestEditProperties)] ComplexModel complexModel)
{
if (ModelState.IsValid)
{
await DocumentDbRepository<ComplexModel>.CreateItemAsync(complexModel);
return RedirectToAction("Index");
}
return View(complexModel);
}
I am currently requesting specific JSON properties to be returned for creating a C# razor view the following way :
CreateAsync([Bind(Include = "list", "of", "about", "50", "strings")]
I'm wondering if it is possible to declare a list of strings somewhere else and referenced variable set somewhere else? Looking for a temporary solution as I am building a prototype and still defining the models of my MVC project. I would like to define what fields I am requesting in a separate file mapped to a variable that describes the query name and holds the list of strings i need to include
Example of declared variables
List<string> DataRequestEditProperties = new List<string> {"bunch", "o", "strings"};
List<string> DataRequestInformativeView = new List<string> {"infoFieldA", "infoFieldB","infoFieldC"};`

Passing list/model as parameter with #url.action

Is there a way to pass list as parameter for #url.action or is there a better solution for this?
Pseudo code:
This doesn't pass anything, unless I define index for my model or list.
#Url.Action("DeleteConfirmed", "Home", new { selectedids = /*model or list?*/ }, null)
I need to pass list or model to this:
public ActionResult DeleteConfirmed(List<int> selectedids) {
//Code
return View("Index");
}
I join them as a string and then convert that back on the server; this means selectedids would need to be a string on the server, which you would string split on comma and convert each value to long.
#Url.Action("DeleteConfirmed", "Home", new { selectedids = String.Join(",", Model.IDS) })

Proper way of passing additional view data to EditorFor

If I pass view data like this
#(Html.EditorFor(x => x.User2, "GenericList",
new ViewDataDictionary {
{ "ListType", ListType.CustomValidation },
{ "Param1", ObjectType.Asset },
{ "Param2", "User2" },
{ "DefaultValue", Model.User2 }
}
))
I am unable to access the Values via ViewData["ListType"]. The keys are stored in a property called Keys, and the values are stored in a ICollection property called Values
Passing the ViewData this way
#Html.EditorFor(x => x.User2, "GenericList",
new { ListType = ListType.CustomValidation,
Param1 = ObjectType.Asset,
Param2 = "User2",
DefaultValue = Model.User2
}
)
means I can get the values easily like ViewData["ListType"].
I don't liek the 2nd method of doing things because it's using anonymous types instead of a ViewDataDictionary. How can I use the first method but still call the ViewData as I expect to be,

pass a list of my model to Transaction in ArangoDB-NET

I simply worked with Transaction in ArnagoDB_NET when I work with one item of my model. but I have a problem when I want to pass a list of my model.
var transactionResult= Context.Transaction.WriteCollection("User").Execute<Dictionary<string, object>>(
string.Format(#"
function () {{
var db = require('internal');
if(!db.User.exists('{0}'))
db.User.save( {{ _key:'{0}', UserAppState:1 }});
}}
// and other actions
return {{ 'Executed': true }};
}}", myModel.userId))
above example fine worked, but when I want to pass a list of my model, how can I iterate them into string(or ArangoDB script)?
for example:
string.Format(#"
function () {{
var db = require('internal');
for (i = 0; i < {0}.count; i++){{ // I know didn't work this block code!
if(!db.User.exists('{i.key}'))
db.User.save( {{ _key: ""'i.key'"", UserAppState:1 }});
// and other actions
}}
return {{ 'Executed': true }};
}}", lstMyModels);
can any one help me?!
I don't think this would be possible given your example, since you are combining C# string interpolated object with ArangoDB transaction functionality which doesn't work together just by combining them into single query.
Your first example works because it's using primitive value which you pass into the string, however in the second example you want to pass list of objects and iterate through them using cycle that is not in any way connected to the list itself. This line
for (i = 0; i < {0}.count; i++) {
won't work because lstMyModels is a C# list object and you would actually end up with a string interpolated like this:
for (i = 0; i < System.Collections.Generic.List`1[System.Object].count; i++) {
which makes no sense to the ArangoDB which needs to execute the transaction. Moreover the i variable is a simple number serving as current cycle iteration index therefore calling i.key is also wrong.
Instead of complicated string interpolation you should try to use transaction parameter passing which is supported by the ArangoDB-NET driver.
EDIT:
Let's say you have object like this:
public class TransactionEntity
{
public string Foo { get; set; }
}
Then you can pass it as transaction parameter for example like this:
var transactionData = new List<TransactionEntity>
{
new TransactionEntity
{
Foo = "string1"
},
new TransactionEntity
{
Foo = "string2"
},
new TransactionEntity
{
Foo = "string3"
}
};
var transactionResult = db.Transaction
.WriteCollection("myCollection")
.Param("data", transactionData)
.Execute<List<TransactionEntity>>(#"
function (params) {
var db = require('internal').db;
for (var i = 0; i < params.data.length; i++) {
db.myCollection.save(params.data[i]);
}
return db._query('FOR doc IN myCollection SORT TO_NUMBER(doc._key) RETURN doc').toArray();
}
");

How to add data to a 2D array in MVC view using HTML helper

I am coding a MVC 5 View, and would like to know how to add data to a hidden 2D array.
Here is my code:
#Html.Hidden("hdnArray")
#for (int i = 0; i < 2; i++)
{
string[] items = new string[4] { "1", "2", "3", "4" };
#Html.HiddenFor(items, { id = "hdnArray" })
}
In the above code, I am trying to add the string[] items array to the hidden 2D array called hdnArray.
I am getting many invalid expression errors at the line:
#Html.HiddenFor(items, { id = "hdnArray" })
Can someone please help me with this?
Thanks in advance.
You are calling HiddenFor incorrectly. If you want to just add hidden inputs that won't be binded to the model then use:
foreach (var item in new int[] {1, 2, 3, 4, 5})
{
#Html.HiddenFor(a => item)
}
But if you're looking to add this to your Model then you should initialize it in the controller before passing it to the view. Then it can be binded by pointing the expression to Model.ArrayItems:
Model:
public class YourModel{
public List<int> ArrayItems { get; set; }
}
View:
foreach (var item in Model.ArrayItems)
{
#Html.HiddenFor(a => Model.ArrayItems)
}

Categories