简体   繁体   中英

C# MVC add records to related table from one view

The background for my C# knowledge is 0. I am trying to learn it as I go. I just am not sure how to use the right words to search. So I am crying for help !

I have a small ASP.Net Web application that uses MVC framework. I have a Database which hold three tables Company , Territory , the third is a relationship table TerritoryCompany . So the basic set up is one Company can have branches in several Territory , and one Territory can have several Company . The relationship is Many-Many .

What I have is a CS Code that will allow you to create a company, nothing fancy, just

    public void Save(CompanyModel company)
    {
        using (var db = new SampleDbContext())
        {
            Company entity;
            if (company.CompanyId > 0)
            {
                entity = db.Companies.First(x => x.Id == company.CompanyId);
            }
            else
            {
                entity = new Company();
                db.Companies.Add(entity);
            }

            entity.Name = company.CompanyName;
            entity.PhoneNo = company.PhoneNo;
            //What should I do?
            db.SaveChanges();
        }
    }

Now as you see, I am able to add the Company Name and Phone Number. Good. This is the code I use in the Webpage,

@model PEF.SampleTesting.Domain.CompanyModel
@{
    ViewBag.Title = "Add";
}
@using (Html.BeginForm("Save", "Companies"))
{
    @Html.EditorForModel()
    <label>Enter the list of service area</label><br />
    <input id="ServiceArea" class="form-control" name="testBox" value="eg. BS1, BA5" /><br/>
    <button type="Submit" class="btn btn-primary">Save</button>
}

Here is the CompaniesController

    [HttpPost]
    public ActionResult Save(CompanyModel model)
    {
        if (!ModelState.IsValid) return View((model.CompanyId == 0)?"Add":"Edit",  model);

        _companyService.Save(model);

        return RedirectToAction("Index");
    }

What I would like to do is, before doing the save changes db.SaveChanges(); when the company is created, I would like to

  • Add these entries for the Territory - if the territory does not exist in the Territory table
  • or
  • Create an entry in the relationship table for that CompanyID and the corresponding TerritoryID ) for that particular Company.

I created a TextBox that will get a comma separated entry of territories. Use this TextBox value in a For and create as many entities to the table Territory (using for loop and split function maybe).

My Questions;

  1. How would I pass the form value (TextBox) back to the code?
  2. How can I use the For Loop to add this 'n' number of entries to the TerritoryCompany table?

Any helps or steps would be greatly appreciated.

Typically instead of passing your data entities to your view you would create a viewmodel, that will provide you with more flexibility...

Something like this class "AddCompanyViewModel", it has a property for your Company and also a property for your comma separated string of territories...

You will now pass this viewmodel too and from your controller instead of the entity type... this is a common scenario as your database structure will rarely perfectly match your domain layer (business layer)... view models essentially model your view.

public class AddCompanyViewModel
{
    public CompanyModel Company { get; set; }
    public string Territories { get; set; }
}


[HttpPost]
public ActionResult Save(AddCompanyViewModel model)
{
    if (!ModelState.IsValid)
        return View((model.Company.CompanyId == 0)?"Add":"Edit",  model);

    _companyService.Save(model.Company);

    // Do something with territories...
    var territories = model.Territories.Split(',');

    return RedirectToAction("Index");
}
  1. You can use the FormCollection parameter for the action.

    public ActionResult Save(CompanyModel model, FormCollection formCol)

Reference the textbox via the name property.

  1. Not quite sure about what you're asking for. You can use the Foreach loop to loop through each territory after you've split the textbox value. Then you create your TerritoryCompany model and save accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM