0

I have a table:.

<% using(Html.BeginForm("View2","Order"))
{  %>  
  <table id="Products" class="Products">
    <tr>
      <th>ProductId</th>
      <th>Productname</th>
      <th>Quantity</th>
      <th>UnitPrice</th>
    </tr>
    <%for (int i = 0; i < Model.NorthOrderDetails.Count; i++)
    {%>
      <%: Html.HiddenFor(m => m.NorthOrderDetails[i].ProductID) %>
      <%: Html.HiddenFor(m => m.NorthOrderDetails[i].ProductName) %>
      <tr>
        <td><%: Html.DisplayFor(m => m.NorthOrderDetails[i].ProductID) %></td>
        <td><%: Html.DisplayFor(m => m.NorthOrderDetails[i].ProductName) %></td>
        <td>
          <input type="hidden" name="NorthOrderDetails.Index" value="<%: i %>" />
          <%: Html.TextBoxFor(m => m.NorthOrderDetails[i].Quantity) %>
        </td>
        <td><%: Html.TextBoxFor(m => m.NorthOrderDetails[i].UnitPrice) %></td>
        <td><button type="button" class="delete" data-id="<%:Model.NorthOrderDetails[i].ProductID %>">Delete</button></td>
        <td> <input type="hidden" name="<%:Model.NorthOrderDetails[i].ProductName %>" value="<%: Model.NorthOrderDetails[i].Quantity %>" /></td>
      </tr>
    <% } %>
  </table>
  <input type="submit" name="button" value="Add" />
  <input type="submit" name="button" value="Save" />
<% } %>

<script type="text/javascript">
  var url = '<%:Url.Action("Delete", "Order")%>';
  $('.delete').click(function () {
    var id = $(this).data('id'); // Get the product ID
    var row = $(this).closest("tr");// Get the table row
    $.post(url, { ID: id }, function () {
      row.remove(); // remove the row from the table when I click the delete button I'm calling this script:
    });
  });
</script>

And the script call this method in the Controller

[HttpPost]
public JsonResult Delete(int ID)
{
  NorthOrder forOrderDetail = (NorthOrder)Session["Order"];
  forOrderDetail.NorthOrderDetails.RemoveAll(z => z.ProductID == ID);
  Session["Order"] = forOrderDetail;
  return Json(null);
}

When I click the add button I'm calling this method in Controller:

[HttpPost]
public ActionResult View2(NorthOrder q,  string button)
{
  string strDDLValue = Request.Form["sda"].ToString();
  int drop = Convert.ToInt32(strDDLValue);
  NorthOrder forOrderDetail = (NorthOrder)Session["Order"];
  if (button == "Add")
  {
    NorthwindEntities n = new NorthwindEntities();
    string strDDLValuse = n.Products.FirstOrDefault(_ => _.ProductID == drop).ProductName;
    NorthOrderDetailscs orddetailForSession = new NorthOrderDetailscs();
    orddetailForSession.ProductName = strDDLValuse;
    orddetailForSession.Quantity = 0;
    orddetailForSession.UnitPrice = 0;
    orddetailForSession.ProductID = drop;
    forOrderDetail.NorthOrderDetails.Add(orddetailForSession);
    Session["Order"] = forOrderDetail;
  }
  return View(forOrderDetail); //
}

and problem concludes displaying data in new row in textboxes from nondeleting item, when I deleted the first item, and after I added new item. Although, in model adding item contains null values for textboxes

In input hidden field Model.NorthOrderDetails[i].Quantity = 0 in new item, as in debug as in markup, but in UI in textbox new item in textbox contains values from existing item

For example, in table two rows

ProductID | ProductName| Quantity| UnitPrice
_____________________________________________
17       |   Chang      |       1       |  12
_____________________________________________
12      |   Chai     |       2      |  24

When I delete first row, and then I add new row I get table

ProductID | ProductName| Quantity| UnitPrice
_____________________________________________
12    |   Chai   |    2    |  24
_____________________________________________
15   |   Allice Mutton    |       2      |  24

What is reason of it?

user4523894
  • 143
  • 1
  • 1
  • 10
  • could not understand your question/problem/issue! can You please edit the last section of your question in order to help us helping you? Sharply yours! – Bellash Mar 09 '15 at 14:14
  • One advice for you: please follow the principles of MVC, since MVC is not WebForm. so DONT USE SESSION IN MVC ANYMORE. When a button is clicked to submit a form via post method, the function automatically called is the one which has `[HttpPost]` attribute...so delete things like `button=="Add"` – Bellash Mar 10 '15 at 09:32

1 Answers1

1

You first need to remove everything relating to storing and retrieving your collection in session. The workflow should be

  1. In the GET method, get the collection and render it in the view.
  2. In the Delete() method, call the database and delete the object based on the ID value. If successful, return Json(true);, if not return Json(null);. In the ajax success function, test if data was returned, if so, delete the row, if not, display error message (refer my answer to your previous questions here and here).
  3. The View2() method should save the collection to the database (remove the string button parameter) and should have no relationship to an Add method.

In order to dynamically add a new item to the DOM which can be bound to your collection, two options are:

  1. Call a method that returns a partial that uses BeginCollectionItem() so that the new item includes an indexer (in the same way that your current for loop is doing). If you use this method, then you could replace your for loop with a simple foreach loop that calls the partial for each item.
  2. Include a html template in the view (inside a hidden element) that you clone and update the Indexer and add it to the DOM.

Both options are discussed in this answer. Note also the need to re-parse the validator each time a new item is added.

Community
  • 1
  • 1
  • Ok. I try to implement it. I use session because I want to call the database only when submit button "Save" use. Other buttons only change UI. When I remove everything connected with Session and work with only model I get the same data in rows, as I describe in question – user4523894 Mar 10 '15 at 06:31
  • 1
    Your not understanding the basic work flow. DO NOT USE SESSION! Your save (submit) button will post back all rows from the view and that's when you update the database (The delete button deletes an item from the database and removes its row so that wont be posted back). Your problems are that (1) you are using session, and (2) your add function needs to add a new single item to the DOM so that can be saved when you click the submit button. You need to read the link I gave in my answer. –  Mar 10 '15 at 06:38
  • All right. I edit my code in project and remove session – user4523894 Mar 10 '15 at 06:43