Doc Robison Doc Robison - 3 months ago 11
C# Question

Array values saved as System.String[] in database

I have a form with checkboxes and posting them back to the controller and saving them to as SQl Server database, the values are System.String[]. Been looking around forums for a bit looking for a solution to output the array back out as a list of selected equipment but not finding anything. When hovering the array in the controller argument, all values that were selected in the form are listed and correct.

<div class="checkbox">
<label>
<input type="checkbox" name="equipmentCheckbox" id="pc" value="PC">PC
</label>
</div>

<div class="checkbox">
<label>
<input type="checkbox" name="equipmentCheckbox" id="monitor" value="Flat Panel Monitor">Monitor
</label>
</div>

<div class="checkbox">
<label>
<input type="checkbox" name="equipmentCheckbox" id="mic" value="mic">Mic
</label>
</div>

<div class="checkbox">
<label>
<input type="checkbox" name="equipmentCheckbox" id="speakers" value="speakers">Speakers
</label>
</div>

<div class="checkbox">
<label>
<input type="checkbox" name="equipmentCheckbox" id="videoPlayer" value="videoPlayer">Video player
</label>
</div>

<div class="checkbox">
<label>
<input type="checkbox" name="equipmentCheckbox" id="lab" value="lab">Lab
</label>
</div>


Controller:

[HttpPost]
public ActionResult equipmentRequest(string[] equipmentCheckbox)
{
var db = new Entities();


string[] equipment = Request.Form.GetValues("equipmentCheckbox");

var order = new Order
{

EquipmentRequested = equipment.ToString(),

};

db.Requests.Add(order);
db.SaveChanges();


return RedirectToAction("Index");
}


I'm stuck on how to parse the array to a list to save correctly to the database instead of System.String[]

Answer

You're trying to use toString on a string array when you do

equipment.ToString() 

I don't know what your purpose is with that .ToString() call, but there is your mistake.

Order should contain

ICollection<EquipmentRequested> EquipmentRequested { get; set; }

instead of

string EquipmentRequested { get; set; }

and EquipmentRequested should contain a string property 'value' and an OrderId to link the objects.