Dean.DePue
Dean.DePue

Reputation: 1013

Set ID for column in foreach loop in MVC4

I am generating a table in MVC4 like this:

 foreach(var item in model.details)
 {
    <tr>
       <td>
           @item.status
       </td>
    </tr>
  }

My question is, how can I assign an ID to that status field? What I want to do is use jQuery and AJAX to modify the value in the database and return with the new status and update only that one column in that one row with the new status, without having to refresh the entire list. I would think that this is the only way to do it, but if there is a better way please let me know.

I have tired

@Html.DisplayFor(model=>item.status, new { @id = "[email protected]"})

and

@Html.DisplayFor(model=>item.status, new { @id = "status" + @item.status})

Neither of which work. I also need to add a click event to the column and can't seem to find a way to do that either.

Upvotes: 0

Views: 2691

Answers (2)

Ramashanker Tripathi
Ramashanker Tripathi

Reputation: 537

@Html.DisplayFor(model=>item.something) can not set Id directly. if you want to use @Html.DisplayFor(model=>item.status) with id you will need some helper.

This is already explained here - Html.DisplayFor — Is it possible to have this control generate an ID

Other wise there is a simple way as-

 foreach(var item in model.details)
     {
        <tr>
           <td id="[email protected](item.status)" class="Clickable_td_class">
               @item.status
           </td>
        </tr>
      }

If you have common status across multiple rows so you need to change your Id unique. you can do this as -

foreach(var item in model.details.Select((x, i) => new { Data = x, Index = i + 1 }))
     {
        <tr>
           <td id="[email protected](item.Data.status)[email protected](item.Index )" class="Clickable_td_class">
               @item.Data.status
           </td>
        </tr>
      }

Please use @Html.Raw(item.status) instead of @item.statusin Id.

Then you can write your jquery something like below -

$("Clickable_td_class").click(function(){
    var current_Id = "#" + $(this).attr("Id");
    $.ajax({
        // All ajax params 
        // and  on success just replace html of particular element as -
        // $(this).html(your success reponse);
        // OR
        //$(current_Id).html(your success reponse);

     });
});

I hope this will solve your problem.

Upvotes: 1

Alex Art.
Alex Art.

Reputation: 8781

UPDATED

Add to each one of your items in the model an Id and for each row set row id property to be equal to this item.Id:

   foreach(var item in model.details)
     {
        <tr id='@item.Id'>
           <td id="[email protected]">
               @item.status
           </td>
        </tr>
      }

And for update (assuming the you receive a json with id and a new value for status)

$ajax(...).done(function(data){    
  $('#status_' +  data.id).html(data.status);
});

Upvotes: 0

Related Questions