Medhanie W.
Medhanie W.

Reputation: 149

Pass updated model to from view to controller using Ajax

I have the following simple class with student firstname and lastname properties. When the view for this model loads, I want to add additional columns to assign cost related information for each row, so that I added two fields in my DOT class i.e. StudentDoaminModel.

The views loads ok, but the value for each of those new properties, Cost1 and Cost2 doesn't pass to controller.

I want to use ajax to pass the model to the controller

Student Model class

public class Student  
{    
    public string first_name{ get; set; }  
    public string last_name { get; set; }      
} 

Student Domain Model class

public class StudentDomainModel  
{    
    public string first_name{ get; set; }  
    public string last_name { get; set; }  
    public int Cost1 { get; set; }
    public Decimal Cost2 { get; set; }    
} 

view

<table id="tblProducts">
    <thead class="text-light bg-dark">
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Cost1</th>
            <th>Cost2</th>
        </tr>
    </thead>
    <tbody>
        @if (Model != null)
        {
            for (int i = 0; i < Model.Count; i++)
            {
        <tr>
            
            <td>
                @Html.DisplayFor(m => m[i].first_name)
                @Html.HiddenFor(m => m[i].first_name)
            </td>
            <td>
                @Html.DisplayFor(m => m[i].last_name)
                @Html.HiddenFor(m => m[i].last_name)
            </td>
            <td>
                @Html.TextBoxFor(m => m[i].Cost1)
                @Html.HiddenFor(m => m[i].Cost1)
            </td>
            <td>
                @Html.TextBoxFor(m => m[i].Cost2)
                @Html.HiddenFor(m => m[i].Cost2)
            </td>
            
        </tr>
            }
        }
    </tbody>

ajax script

<script>
$("#export").click(function (event)
{
var object = @(Html.Raw(Json.Encode(Model)));
$.ajax({
        type: 'POST',
        url: '/Student/StudentData',
        data: JSON.stringify({ modelData: object }),
        contentType: 'application/json',
        dataType: 'json',
        success: function (response)
        {
            if (response != '')
                console.log("Success");
        },
        failure: function (response)
        {
            console.log("Failure");
        },
        error: function (response)
        {
            console.log("Error:" + response);
        }
    });
});
</script>

In my controller, I am getting 0 for both Cost1 and Cost2, how do I pass the new value for each columns?

Upvotes: 1

Views: 102

Answers (1)

Ghanat
Ghanat

Reputation: 168

I have changed previous answer to this one:

1- View Code:

<table>
    @if (Model != null)
    {

        foreach (var item in Model.ToList())
        {
            <tr class="studentItem">
                <td>
                    @item.first_name
                    @Html.Hidden("first_name", item.first_name)
                </td>
                <td>
                    @item.last_name
                    @Html.Hidden("last_name", item.last_name)
                </td>
                <td>
                    @Html.TextBox("Cost1", item.Cost1)
                </td>
                <td>
                    @Html.TextBox("Cost2", item.Cost2)
                </td>
            </tr>
        }
    }
</table>

<input type="button" id="export" title="export" value="export" />

2- Use this script to make a JSON string (formJsonData) form elements and send to server:

<script>
    $("#export").click(function (event) {


        var formJsonData = "[";

        for (var i = 0; i < $(".studentItem").length; i++) {
            formJsonData = formJsonData + "{";

            var first_name = $("input[name='first_name']")[i];
            formJsonData = formJsonData + "\"first_name\":" + "\"" + first_name.value + "\",";
            var last_name = $("input[name='last_name']")[i];
            formJsonData = formJsonData + "\"last_name\":" + "\"" + last_name.value + "\",";
            var Cost1 = $("input[name='Cost1']")[i];
            formJsonData = formJsonData + "\"Cost1\":" + Cost1.value + ",";
            var Cost2 = $("input[name='Cost2']")[i];
            formJsonData = formJsonData + "\"Cost2\":" + Cost2.value;

            formJsonData = formJsonData + "},";
        }      
        formJsonData = formJsonData + "]";


        $.ajax({
            type: 'POST',
            url: '/Student/StudentData',
            data: { 'formResult': formJsonData },
            success: function (response) {
                if (response != '')
                    console.log("Success");
            },
            failure: function (response) {
                console.log("Failure");
            },
            error: function (response) {
                console.log("Error:" + response);
            }
        });
    });



</script>

3- I have used a controller class like this with some mock datas:

public class StudentController : Controller
{
    public ActionResult Index()
    {
        List<StudentDomainModel> list = new List<StudentDomainModel>();
        list.Add(new StudentDomainModel { first_name = "a", last_name = "aa", Cost1 = 11, Cost2 = 12 });
        list.Add(new StudentDomainModel { first_name = "b", last_name = "bb", Cost1 = 21, Cost2 = 22 });
        list.Add(new StudentDomainModel { first_name = "cc", last_name = "cc", Cost1 = 31, Cost2 = 32 });
        list.Add(new StudentDomainModel { first_name = "dd", last_name = "dd", Cost1 = 41, Cost2 = 42 });
        var foo = JsonConvert.SerializeObject(list);
        return View(list);
    }

    [HttpPost]
    public JsonResult StudentData(string formResult)
    {
        List<StudentDomainModel> list = JsonConvert.DeserializeObject<List<StudentDomainModel>>(formResult);
        return null;
    }
}

Uploaded Sample Project: https://github.com/mghanatabady/MvcTableFromSample

Upvotes: 2

Related Questions