Dashamlav
Dashamlav

Reputation: 245

How to bind HTML label to Model so that it displays data?

I have a list that I am sending to the View from GET Method with the help of a ViewModel. I plan to send the list data to the View just to display it on the screen. I want this label to display the list data one-by-one in the view in a label (since I do not want to edit the data). Then, upon hitting SUBMIT, I want the same list data to be sent to the POST method where I will be able to save the data. Also, I want to do this without using HTML Helpers.

Here is what I have:

MyView.cshtml

<html>
    ...
    <table class="table table-striped table-bordered" id="myTable"> 
        <thead>
            <tr>
                <th>Items</th>
            </tr>
        </thead>
        <tbody>
            @for (var i = 0; i < Model.MyList.Count(); i++)
            {
                <tr>
                    <td>
                        // This is where I want to display the label. 
                        <label name="MyList[@i]">@Model.MyList[i].ToString()</label>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</html>

MyController.cs

[HttpPost]
public ActionResult MyMethod(MyViewModel VMObject)
{
    ...
}

I am able to display the list contents in the view with <label name="MyList[@i]">@Model.MyList[i].ToString()</label>. But, the ViewModel object that is returned in POST method shows that the list is null. Where am I going wrong?

Edit - 07/31

MyViewModel.cs

public class MyViewModel
{
    public int ID { get; set; }
    public string ItemCode { get; set; }
    public int ItemId { get; set; }
    public string ItemName { get; set; }

    public List<string> MyList { get; set; }
}

Upvotes: 0

Views: 2204

Answers (2)

Keith
Keith

Reputation: 276

Since you don't want to use the html helpers you might looking for an ajax request

You could use this script and place this in the click event of your submit button.

$.ajax({
        url: '@Url.Content("~/*CONTROLLERNAME*/MyMethod")',
        type: 'POST',
        dataType: json,
        data:  @Html.Raw(Json.Encode(Model)),
        success: function (data) {
        }
    });

By using @Html.Raw(Json.Encode(Model)) you are converting the View Model into Json data that is readable by the ajax request.

Upvotes: 0

Jerdine Sabio
Jerdine Sabio

Reputation: 6185

You might need to add a hidden input field. Hence your loop will look like;

@for (var i = 0; i < Model.MyList.Count(); i++)
{
   <tr>
     <td> 
       <label>@Model.MyList[i].ToString()</label>
       <input name="MyList[@i]" value="@MyList[i].ToString()" hidden />
     </td>
   </tr>
}

Upvotes: 1

Related Questions