0

I'm having some trouble on the concept of saving multiple child for what I need on MVC 5. The entity comes from a currency pair graph on a daily basis that would be the parent. And what I need its to create the parent, lets say Euro/Dollar and then assign important levels that can be one, two, or ten. So I know I could create the parent and then in other step create the childs but its not very "friendly" as it has to be done for lots of currency pairs and everyday. I wonder if theres a way to do this all in a single page. I don't know if I'm being clear with what I want, but as a concept I think it is like adding tags to a blog, you create the "blog article" and add tags all at same page but you don't know how many tags the article will have.

This are my models

public class Pair
{
    public int pairID { get; set; }
    public string name { get; set; }
    public DateTime Date { get; set; }
    public virtual IEnumerable<Levels> Levels { get; set; }
}

public class Levels
{
    public int levelID { get; set; }
    public double Value { get; set; }
    public string comment { get; set; }
    public int pairID { get; set; }
    public virtual Pair Pair { get; set; }
}
Krash
  • 31
  • 2
  • You can save parent child records from single page for sure, but I couldn't understand your requirement clearly. – Badhon Jain Aug 23 '15 at 04:31
  • Well the question is how. Like how to assign the parent ID to the childs if its been created with same button. – Krash Aug 23 '15 at 05:01
  • Some examples [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) –  Aug 23 '15 at 11:16

2 Answers2

0

There are two ways I can think of for achieving what you want:

  • If the number of child records that you want is limited then you can achieve this without the use of any JavaScript.

Example:

This example will only allow you to add 5 Levels per Pair. If you want you can just change the following code to increase the number of Levels

Levels = Enumerable.Range(1, 5).Select(i => new Levels()).ToList();

Model

public class Pair
{
    public Pair()
    {
        Levels = Enumerable.Range(1, 5).Select(i => new Levels()).ToList();
    }  
    ....
}

public class Levels
{
    ....
}

Controller

[HttpGet]
public ActionResult ExampleParentChild()
{
    return View(new Pair());
}

[HttpPost]
public ActionResult ExampleParentChild(Pair pair)
{
    if (ModelState.IsValid)
    {
        context.Pairs.Add(pair);
        context.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(pair);
}

View

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    @Html.LabelFor(m=> m.Date)
    @Html.EditorFor(m=>m.Date)

    @foreach(var item in Model.Levels)
    {
        @Html.LabelFor(m=> item.Value)
        @Html.EditorFor(m=> item.Value)

        @Html.LabelFor(m=> item.comment)
        @Html.EditorFor(m=> item.comment)
    }

    <input type="submit" value="Create" />
}
  • If you want the number of child records to be dynamic then you will have to use JavaScript to be able to add more input elements to the page on the run. You can either use jQuery or AngularJS. I am providing you an example with the use of AngularJS and WEB API, the reason I am providing you an example with AngularJs is that you asked to do it in a single page and everyone uses AngularJS nowadays for SPAs.

Example:

AngularController

angular.module('Pair', [])
    .controller('PairController', PairController);
function AccountController($http) {
    vm.Pair = {};
    vm.Pair.Levels = []
    vm.addLevel = function(){
        if (vm.Pair.Levels)
        {
            vm.Pair.Levels.push({});
        }
    };
    vm.savePair = function () {
        $http.post('/api/PairsApi/', vm.Pair).success(function (data) {
            vm.Pair = {};
        }).error(function (data) {
            // code for error
        });
    };
};

WEBAPI

[Route("api/PairApi/{id?}", Name = "api_PairApi")]
public class PairLedgersApiController : ApiBaseController 
{
    DbContext _db = new DbContext();
    public IHttpActionResult PostPairLedger(Pair pair)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _db.Pairs.Add(pair);
        _db.Save();

        return CreatedAtRoute("api_PairApi", new { id = pair.Id }, Pair);
    }
.....
}

View

<div data-ng-app="Pair" data-ng-controller="PairController as vm">
    <form name="PairForm" ng-submit="vm.savePair()" novalidate>
        <div class="form-body">
            <label>Name</label>
            <input type="text" name="pairName" ng-model="vm.Pair.name " class="form-control"/>

            <label>Date</label>
            <input type="date" name="pairDate" ng-model="vm.Pair.Date" value="{{vm.Pair.Date | date: 'yyyy-MM-dd'}}" class="form-control"/>

            <div ng-repeat="level in vm.Pair.Levels">
                <label>Value</label>
                <input type="text" name="levelValue" ng-model="level.value" class="form-control"/>

                <label>Comment</label>
                <input type="text" name="levelComment" ng-model="level.comment" class="form-control"/>
            </div>
            <input type="submit" value="Save" class="btn blue" />
            <button ng-click="vm.addLevel();" class="btn blue">
                Add Level
            </button>
        </div>
    </form>
</div>

If you are new to AngularJS, you can refer to the following links for using it with ASP .NET MVC:

Build a Single Page Application (SPA) with ASP.NET Web API and Angular.js

CRUD with SPA, ASP.NET Web API and Angular.js

Syed Farjad Zia Zaidi
  • 3,302
  • 4
  • 27
  • 50
-1
public long Save(INVStoreTrans model, int userId, string pageUrl)
    {
        long CurrentTransactionID = 0;

        try
        {
            using (TransactionScope transaction = new TransactionScope())
            {

                using (_context)
                {
                    var GetTransactionNo = DalCommon.GetPreDefineNextCodeByUrl(pageUrl);

                    if (GetTransactionNo != null)
                    {
                        #region New_Transaction_Insert

                        INV_StoreTrans objIssue = new INV_StoreTrans();

                        objIssue.TransactionNo = GetTransactionNo;
                        objIssue.TransactionDate = DalCommon.SetDate(model.TransactionDate);
                        objIssue.TransactionCategory = "ISU";
                        objIssue.TransactionType = "STI";
                        objIssue.TransactionFrom = model.IssueFrom;
                        objIssue.TransactionTo = model.IssueTo;

                        objIssue.TransactionStatus = "TRI";


                        objIssue.RecordStatus = "NCF";
                        objIssue.SetBy = userId;
                        objIssue.SetOn = DateTime.Now;

                        _context.INV_StoreTrans.Add(objIssue);
                        _context.SaveChanges();
                        CurrentTransactionID = objIssue.TransactionID;
                        #endregion

                        #region Item Insert
                        if (model.TransactionItemList != null)
                        {
                            foreach (var item in model.TransactionItemList)
                            {
                                INV_StoreTransItem objItem = new INV_StoreTransItem();

                                objItem.TransactionID = CurrentTransactionID;

                                objItem.ItemID = item.ItemID;
                                objItem.SupplierID = item.SupplierID;

                                objItem.TransactionQty = item.IssueQty;

                                objItem.TransactionUnit = DalCommon.GetUnitCode(item.IssueUnitName);


                                objItem.PackSize = DalCommon.GetSizeCode(item.IssuePackSizeName);
                                objItem.SizeUnit = DalCommon.GetUnitCode(item.IssueSizeUnitName);


                                objItem.PackQty = item.IssuePackQty;
                                //objItem.ItemSource = DalCommon.ReturnItemSource(item.ItemSource);
                                objItem.SetOn = DateTime.Now;
                                objItem.SetBy = userId;

                                _context.INV_StoreTransItem.Add(objItem);
                                //_context.SaveChanges();
                            }

                        }
                        #endregion
                    }
                    _context.SaveChanges();

                }
                transaction.Complete();
            }
            return CurrentTransactionID;
        }
        catch (Exception e)
        {
            return 0;
        }
    }
Badhon Jain
  • 938
  • 6
  • 20
  • 38