How do you initialize a FormCollection with properties in .NET?
Asked Answered
V

2

9

I've tried the usual way of:

var form = new FormCollection { "WeekList" = weekfilter, "PracticeList" = practicefilter}

and all possible deviations I could think of, but ultimately had to seperate it apart as:

var form = new FormCollection();
form["WeekList"] = weekfilter;
form["PracticeList"] = practicefilter;

How can I initialize this inline? Is it possible? (I'm basically trying to mimic a form being submitted)

Vulgar answered 18/3, 2014 at 18:11 Comment(1)
ideally you should be using model bindingWonderstricken
G
15

If you're using ASP.NET MVC (not core), you can initialize System.Web.Mvc.FormCollection like this:

var form = new FormCollection {
    {"WeekList", weekfilter},
    {"PracticeList", practicefitler}
}

Demo in .NET Fiddle

But I'm not the right computer to test this. I'm basing this on the .Add method of FormCollection begin declared as:

public virtual void Add(
    string name,
    string value
)

What types are the filter variables declared as?

Gaol answered 18/3, 2014 at 18:32 Comment(0)
A
4

If you're using Microsoft.AspNetCore.Http.FormCollection in aspnet core, you can initialize like this:

var formCol = new FormCollection(new Dictionary<string, Microsoft.Extensions.Primitives.StringValues>
{
    { "Field1", "String Value 1" },
    { "Field2", "String Value 2" },
    { "Field3", "String Value 3" }
});

Demo in .NET Fiddle

Then, if you need to create a controller with test data, you can pass to the controller create method like this:

// Call create controller with test data
_controller.Create(formCol);
Afterclap answered 10/6, 2019 at 18:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.