简体   繁体   English

C#MVC从一个视图向相关表添加记录

[英]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. 我的C#知识背景为0。我正在尝试学习它。 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. 我有一个使用MVC框架的小型ASP.Net Web应用程序。 I have a Database which hold three tables Company , Territory , the third is a relationship table TerritoryCompany . 我有一个数据库,其中包含三个表CompanyTerritory ,第三个是关系表TerritoryCompany So the basic set up is one Company can have branches in several Territory , and one Territory can have several Company . 因此,基本设置是:一个Company可以在多个Territory设有分支机构,而一个Territory可以拥有多个Company The relationship is Many-Many . 这种关系是Many-Many

What I have is a CS Code that will allow you to create a company, nothing fancy, just 我所拥有的是一个CS代码,可以让您创建一家公司,没什么特别的,

    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 这是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(); 我想做的是,在进行保存更改之前,先执行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 为“ Territory添加这些条目-如果“领土”表中不存在该Territory
  • or 要么
  • Create an entry in the relationship table for that CompanyID and the corresponding TerritoryID ) for that particular Company. 在关系表中为该公司ID和该特定公司的对应TerritoryID( )创建一个条目。

I created a TextBox that will get a comma separated entry of territories. 我创建了一个TextBox ,它将获得用逗号分隔的区域条目。 Use this TextBox value in a For and create as many entities to the table Territory (using for loop and split function maybe). 在For中使用此TextBox值,并为表Territory创建尽可能多的实体(可能使用for循环和拆分功能)。

My Questions; 我的问题;

  1. How would I pass the form value (TextBox) back to the code? 如何将表单值(TextBox)传递回代码?
  2. How can I use the For Loop to add this 'n' number of entries to the TerritoryCompany table? 如何使用For循环将此“ n”个条目添加到TerritoryCompany表中?

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... 类似于此类“ AddCompanyViewModel”,它为您的公司提供一个属性,并为您的逗号分隔的领土字符串提供一个属性...

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. 现在,您也将通过控制器而不是实体类型传递此viewmodel ...这是一种常见情况,因为您的数据库结构很少会与您的域层(业务层)完全匹配...视图模型实质上是对视图进行建模。

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. 您可以将FormCollection参数用于操作。

    public ActionResult Save(CompanyModel model, FormCollection formCol) 公共ActionResult保存(CompanyModel模型,FormCollection formCol)

Reference the textbox via the name property. 通过name属性引用文本框。

  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. 拆分文本框值后,可以使用Foreach循环遍历每个区域。 Then you create your TerritoryCompany model and save accordingly. 然后,您创建TerritoryCompany模型并进行相应保存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.net MVC / EF / C#不添加任何相关表记录以在控制器中查询 - ASP.net MVC/EF/C# add none related table records to query in controller 从MVC C#中的单个视图对不同表中的多个相关记录进行CRUD操作 - CRUD operations for multiple related records in different tables from single view in MVC C# 如何在Asp.net MVC C#中使用Linq从一个表中选择具有最大计数值的多个表中的记录# - how to select records from multiple table with max count value from one table using Linq in Asp.net MVC C# 如何在C#中基于表格的一列显示记录? - how to display records based on one column from table in c#? 可编辑记录表中的C#MVC DropDownListFor - C# MVC DropDownListFor in a table of editable records C#MVC2如何在不同的列中添加两个相关表的数据? - C# MVC2 how to add data two related table in different column? C#MVC:从视图向ViewModel动态添加对象 - C# MVC: Dynamically Add Object To ViewModel From View 使用C#/ Razor MVC将数据从表传递到控制器 - Pass Data to Controller from Table in View with C#/Razor MVC 从一个表中选择记录,检查它是否在另一个表中,然后插入C#中的第三个表中 - Select records from one table, check if it exists in another table then insert into a 3rd table in C# 从第三个表中选择与两个联接表之一相关的记录 - Selecting records from a third table that is related to one of the two joined tables
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM