-2

Here is my code:

Controller:

public ActionResult InsertData(CoModel coModel)
{
    if (ModelState.IsValid)
    {
        db.Entry(coModel).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(coModel);
}   

Model:

public class CoModel
{
    [Key]
    public int id { get; set; }      
    public string item_no { get; set; }       
    public string destination { get; set; }      
    public int total_piece { get; set; }
}   

View:

@using (Html.BeginForm("InsertData", "ControllerName", FormMethod.Post, new { Id = "Form1"}))
{
    @foreach (var item in Model)
    {
        @Html.DisplayFor(modelItem => item.item_no)  @Html.HiddenFor(model => item.item_no)
        @Html.DisplayFor(modelItem => item.destination) @Html.HiddenFor(model => item.destination) 
        @Html.DisplayFor(modelItem => item.total_piece) @Html.HiddenFor(model => item.total_piece)
        <button type="submit">Save</button>
    }
}

Here is my question. Why every time I pressed the Save button the controller receives null/zero value? Is my coding wrong?

Nosbig
  • 1
  • 1
  • 4
  • 1
    What is the point of this - all your controls are hidden inputs and you cannot even edit anything. And the model in the view is a collection, not a single `CoModel` object to the POST method also needs to be `List`. But in any case, you cannot use a `foreach` loop to generate form controls for collection items (refer [this answer](http://stackoverflow.com/questions/30094047/post-an-html-table-to-ado-net-datatable/30094943#30094943)). –  Oct 09 '16 at 06:19
  • Because this is from a view result. I want to insert in to another table. That is why I dont need to enter the value. – Nosbig Oct 09 '16 at 06:21
  • Sending a whole lot of hidden inputs to the view and sending them all back again unchanged makes no sense (and neither does you last comment) –  Oct 09 '16 at 06:24
  • Ok. I will try to redo my codes. Thank you for the insight. – Nosbig Oct 09 '16 at 06:34

1 Answers1

0

You are using DisplayFor that is hidden. You must use EditorFor, TextBox, TextBoxFor, TextArea and others that render input HTML type different of hidden.

Almeida
  • 1,254
  • 12
  • 26
  • I already tried the EditorFor, TextBox, TextBoxFor and others but always return null value. – Nosbig Oct 09 '16 at 10:11