1

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?

6
  • I have added an answer If you think it is not clear, let me know, I can make it simpler and add some server side code with a class for deserilization. @Medhanie W. Commented Sep 24, 2020 at 5:59
  • Thanks @Ghanat the model is List type List<StudentDomainModel> I am getting null, this is my controller [HttpPost] public FileStreamResult StudentData(List<StudentDomainModel> modelData) { } Commented Sep 25, 2020 at 2:05
  • 1
    You're welcome, I edited the answer fully. and add a tested controller layer Commented Sep 25, 2020 at 4:46
  • @Ghanat thank you a lot, I really appreciate your time, but still i am getting null in my controller, I changed data: { 'formResult': formJsonData }, to data: JSON.stringify(formJsonData), but still getting null in my controller Commented Sep 25, 2020 at 7:53
  • 1
    @Medhaine W. I haven't got any problem in my local solution, I have uploaded my solution on github github.com/mghanatabady/MvcTableFromSample Commented Sep 25, 2020 at 8:54

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

How should I accept in my controller? I am getting null, this is my controller [HttpPost] public FileStreamResult StudentData(List<StudentDomainModel> modelData) { }
@MedhanieW. I have changed the answer, I used another approach and wrote a controller too. The result passed the test. everything is ok now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.