0

what I try to do is to bind every incomming value from my response to a string or stringlist dynamicly / generic.

So assume I would know each POST-Value of my request, e.g.

string1 = Test
string2 = Test2

I would write:

[HttpPost]
public ActionResult DoFoo(string string1, string string2)
{
}

or

[HttpPost]
public ActionResult DoFoo(string string1, [Bind(Prefix = "string2")string myString2)
{
}

My situation know is, that I have X strings with my post request. So I dont know the exact number nor the names to catch in my backend. How to catch every given Post-value without knowing this / how to catch the values dynamicly?

poke
  • 369,085
  • 72
  • 557
  • 602
Rene Koch
  • 317
  • 3
  • 13
  • How about a dictionary? How about you directly use `Request.QueryString["string2"]`? – Aron Sep 15 '15 at 06:41

1 Answers1

1

I don't feel that why you have to use Prefix with BIND, when you have to bind every incoming field of response. Bind is not a good choice for that. You can use bind if you have multiple entities at the same time. Reference here

that I have X strings with my post request.

If you have to use all the fields then you can use FormCollection or Model object to receive those fields. FormCollection automatically receive all the fields from view and bind them to a collection. See this for proper example. And a code snippet is below for reference.

[HttpPost]
public ActionResult Create(FormCollection collection)
{
    try
    {   
        Student student = new Student();

        student.FirstName = collection["FirstName"];
        student.LastName = collection["LastName"];
        DateTime suppliedDate;
        DateTime.TryParse(collection["DOB"], out suppliedDate);
        student.DOB = suppliedDate;
        student.FathersName = collection["FathersName"];
        student.MothersName = collection["MothersName"];

        studentsList.Add(student);
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

However if you have to deal with only one particular field/set of fields then you can use either Include or Exclude as per your convenience with BIND. Example shown here and code snipped is added below.

In following way you are telling that you only want to include "FirstName" of User model while receiving the form content. Everything else will be discarded.

[HttpPost]
public ViewResult Edit([Bind(Include = "FirstName")] User user)
{
    // ...
}

And in following example you are telling that, please exclude "IsAdmin" field while receiving the fields. In this case, value of IsAdmin will be NULL, irrespective of any data entered/modified by end-user in view. However, in this way, except IsAdmin, data rest of the fields will be available with user object.

[HttpPost]
public ViewResult Edit([Bind(Exclude = "IsAdmin")] User user)
{
    // ...
}
Community
  • 1
  • 1
Amnesh Goel
  • 2,617
  • 3
  • 28
  • 47