1

I am new to MVC and I am trying to understand how this whole Model binds to a view. I understood how to display any complex object using a partial view / views but I am not able to understand how to create an object of the model using a view.

We have a card to which we can add multiple transactions on the go .

Essentially what I am trying to achieve is this view to add transactions. The Add transactions button when clicked adds a partial view to the div tag on the main page. When I hit save all these transactions have to be added to the AcctCardTransaction model and then be sent to the controller. I am not able to add the UI of my page as the site does not allow me to add it . All I am trying to do is to display a partial view that binds to the model and creates a list of transactions so that the model can be used to save to the tables.

[![Add Card # and Transactions][1]][1]

Here is the model for the Card Transactions

public class AcctCardTransaction
{
    public int? LastFourAcctNumber { get; set; }
    public int LastFourDigCard { get; set; }
    public List<Transaction> AssociatedTransactions { get; set; }
}

Transactions:

public class Transaction
{
    public bool isSelected { get; set; }
    public int Amount { get; set; }
    public DateTime TransDateTime { get; set; }
    public string Location { get; set; }
    public string Desc1 { get; set; }
    public string Desc2 { get; set; }
    public string Desc3 { get; set; }
}

Here is the partial view to add one transaction - on to the screen

@model UI.Data.Models.Claim.Transactions.Transaction

@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<div class="row">
    <div class="col-md-1">
        <br />
        @Html.CheckBoxFor(model => model.isSelected)
    </div>
    <div class="col-md-2">
        @Html.LabelFor(model => model.Amount) <label>:</label>
        @Html.EditorFor(model => model.Amount)
    </div>

    <div class="col-md-2">
        @Html.LabelFor(model => model.TransDateTime)
        @Html.EditorFor(model => model.TransDateTime)
        @Html.ValidationMessageFor(model => model.TransDateTime)
    </div>


    <div class="col-md-2">
        @Html.LabelFor(model => model.Location)
        @Html.EditorFor(model => model.Location)
        @Html.ValidationMessageFor(model => model.Location)

    </div>

    <div class="col-md-2">
        @Html.LabelFor(model => model.Desc1)

        @Html.EditorFor(model => model.Desc1)
        @Html.ValidationMessageFor(model => model.Desc1)

    </div>
    <div class="col-md-1">
        <br />
        <a href="#" onclick="$(this).parent().parent().remove();" style="float:right;">Delete</a>
    </div>      
</div>

[![enter image description here][1]][1]

Here is the view to add card # and transaction

@model AcctCardTransaction 
@{
    ViewBag.Title = "Add Transactions";
}
@using (Html.BeginForm("AddTransactions", "Prepaid"))
{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnAddTran").click(function () {
                $.ajax({
                    url: '/Prepaid/AddOneTransaction',
                    contentType: 'application/html; charset=utf-8',
                    type: 'GET',
                    dataType: 'html'

                }).success(function (result) {
                    $('#addTransDiv').append(result);

                })
                        .error(function (xhr, status) {
                            alert(status);
                        });
            });
        });
    </script>

    <div class="form-inline bottom-left">
        <div class="row">
            @Html.Label("Last 4 digits of the card")
            @Html.EditorFor(model => model.LastFourDigCard)
            @Html.ValidationMessageFor(model => model.LastFourDigCard)

          @*   @Html.Partial(  "~/Views/Shared/Partials/_addTransaction.cshtml")*@


            <input id="btnAddTran" value="Add Transaction" class="btn btn-default pull-right" />
        </div>
    </div>
    <br />

    <div class="row" id="addTransDiv">
        <hr />
    </div>

    <input type="submit" value="save" class="btn btn-default pull-right" />    
}

Here is my simple controller . AddoneTransaction is the action that adds one transaction partial view to the view. In my httpPost AddTransactions action The model object does not return any transactions.

Here is my exact question. how do i bind these transactions Model objects that are returned from these partial views as a list to the main model object card transactions and from there return this to the controller?

[HttpGet]
public ActionResult AddTransactions()
{
    AcctCardTransaction acctCardtran = new AcctCardTransaction();
    return View(acctCardtran);
}

[HttpPost]  
public ActionResult AddTransactions(AcctCardTransaction cardTrans)
{
    return View();
}

public ActionResult AddOneTransaction()
{
    Transaction nTran = new Transaction();
   return PartialView("~/Views/Shared/Partials/_addTransaction.cshtml",nTran);
}

I tried a lot of find answer for this question and could not understand what others were talking about , I saw lots of posts on how to display an existing model with a list of objects , but here I want to create and not just display.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Erin
  • 41
  • 7
  • You current implementation is just adding elements with duplicate `name` attributes (without indexers so cannot be bound to a collection) and duplicate `id` attributes (invalid html). You can use the `BeginCollectionItem` helper or use a pure client side solution for dynamically adding and deleting collection items as discussed [here](http://stackoverflow.com/questions/29161481/post-a-form-array-without-successful/29161796#29161796) and [here](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) –  Sep 09 '15 at 01:44

1 Answers1

0

You are providing two different models to both views and expecting that they would be bound to one Model somehow and would return the single Model on post. It doesn't make any sense.

....but I am not able to understand how to create an object of the model using a view.

Also you are rendering your Partial view using custom javascript. So you have to write a JS method to find the form and build the model from all added partial views(transactions) and then post it to the server.

$('button.submitTransaction').click(function (e) {

    // Sample to find all div containing all added transactions type
    var form = $('#AddTransactions').find('form');

    // validate the form
    var v = $(form).valid();

    if (v === true) {

        var transactionsContainer = $('#AddTransactions').find('row');

        // Loop through the transaction div container
        // Find your model properties from fields

        var transactions = [];
        // Fill transaction related information in the array
        // e.g. Find Amount's value and other properties in a Row with in the loop

        var transaction = { 
            'Amount': Amount, 
            'TransDateTime': TransDateTime,
            'Location': Location,
            'Desc1': Desc1
        }

        transactions.push(transaction);

        // user your actual post url here 
        // Data would be automatically deserialized to the model i.e. AcctCardTransaction
        var jqreq = $.post('/Prepaid',
            {
                'LastFourAcctNumber': lastFourAccNo,
                'LastFourDigCard': lastFourDigCard,
                'Description': description,
                'AssociatedTransactions': transactions
            });

        jqxhrjqreq.done(function (data) {
            if (data === true) {
                alert('Success!!');
            } else {
                onError(null);
            }
        });

        jqreq.fail(function (e) {
            onError(e);
        });
    }
    return false;
});
vendettamit
  • 14,315
  • 2
  • 32
  • 54
  • As I said I am new to MVC so I am trying to understand how it works , I thought the model still exists after it is sent to the client. I will try this way for sure! – Erin Sep 09 '15 at 15:36