【问题标题】:Insert Data using models with ASP.NET Core and EF Core 1.1使用具有 ASP.NET Core 和 EF Core 1.1 的模型插入数据
【发布时间】:2017-04-13 12:32:32
【问题描述】:

我对我的代码有疑问,

我的主要目标是插入来自模型的数据,在该模型中我设置了多个模型来获取数据。这是我的 Model 中的代码:

public class ModelLoan
{
    public SelectList employees { get; set; }
    public SelectList collectors { get; set; }
    public SelectList loanTypes { get; set; }
    public SelectList loanStatus { get; set; }
    public SelectList loanFrequency { get; set; }
    public LoanContract loanContract { get; set; }
}

控制器

public IActionResult Index()
    {
        //For Employees List
        var lstEmployee = _Context.Employee.OrderBy(e => e.Fname + ' ' + e.Lname).Select(x => new { Id = x.EmployeeId, Value = x.Fname + ' ' + x.Lname });
        //For Collectors List
        var lstCollector = _Context.Collectors.OrderBy(c => c.CollectorName).Select(x => new { Id = x.CollectorId, Value = x.CollectorName});
        //For Loan Type List
        var lstLoanType = _Context.LoanType.OrderBy(lt => lt.Description).Select(x => new { Id = x.LoanTypeId, Value = x.Description });
        //For Loan Status List
        var lstLoanStatus = _Context.LoanStatus.OrderBy(ls => ls.StatusName).Select(x => new { Id = x.LoanStatusId, Value = x.StatusName });
        //For Loan Frequency List
        var lstLoanFrequency = _Context.LoanFrequency.OrderBy(lf => lf.LoanFrequencyId).Select(x => new { Id = x.LoanFrequencyId, Value = x.Description });

        var myList = new ModelLoan();
        myList.employees = new SelectList(lstEmployee, "Id", "Value");
        myList.collectors = new SelectList(lstCollector, "Id", "Value");
        myList.loanTypes = new SelectList(lstLoanType, "Id", "Value");
        myList.loanStatus = new SelectList(lstLoanStatus, "Id", "Value", 1003);
        myList.loanFrequency = new SelectList(lstLoanFrequency, "Id", "Value", 2);

        //Set Default
        return View(myList);
    }

现在我将这些数据放在SelectList 方法上,我很容易通过使用<select> 标签查看。但问题是我不知道如何提取它的value

现在这是我的观点:

@model prjPEMCOLoan.Models.ModelLoan

 

<form asp-controller="Loan" asp-action="SaveLoanContract" role="form" method="post" style="padding-top: 2em;">
    <h2>Loan Application</h2>
    <div class="form-group">
        <label>Select Employee</label>
        <select class="form-control" name="lc.loanContract.EmployeeId"  asp-items="@Model.employees"></select>
        <small class="form-text text-muted">Select the specific employee. If employee name is not on the list then you register the employee <a asp-controller="Employee" asp-action="Index">here</a>.</small>
        <span asp-validation-summary="All"></span>
    </div>

    <div class="form-group">
        <label>Select Collector</label>
        <select class="form-control" name="lc.loanContract.CollectorId" asp-items="@Model.collectors"></select>
        <small class="form-text text-muted">Collector will be the one to check your loan status in this system.  He/She will be the responsible for accepting/rejecting your loan applied.</small>
        <span asp-validation-summary="All"></span>
    </div>

    <div class="form-group">
        <label>Select Loan Type</label>
        <select class="form-control" name="lc.loanContract.LoanTypeId" asp-items="@Model.loanTypes"></select>
        <small class="form-text text-muted">Choose your desired loan type you want to apply.</small>
        <span asp-validation-summary="All"></span>
    </div>

    <div class="form-group">
        <label>Status</label>
        <select class="form-control" name="lc.loanContract.LoanStatusId" asp-items="@Model.loanStatus" disabled></select>
        <small class="form-text text-muted">Upon registration to this loan you are set to pending status as default to check your loan by the collectors.</small>
        <span asp-validation-summary="All"></span>
    </div>

    <div class="form-group">
        <label>Status</label>
        <select class="form-control" name="lc.loanContract.LoanFrequencyId" asp-items="@Model.loanFrequency" disabled></select>
        <small class="form-text text-muted">Upon registration to this loan you are set to a <b>Biweekly</b> because your payroll mostly computed and deducted every Biweekly day of the month.</small>
        <span asp-validation-summary="All"></span>
    </div>

    <div class="form-inline">
        <div class="form-group">
            <label> Date Applied: </label><span> </span>
            <input disabled type="date" name="lc.loanContract.LoanDateStart" id="dpDateNow" class="form-control" /><br />
            <small class="form-text text-muted">This is the date you applied.</small>
            <span asp-validation-summary="All"></span>
        </div>
        <div class="form-group">
            <label> Date Approved: </label><span> </span>
            <input type="date" id="dpDateApproved" name="lc.loanContract.LoanDateEnd" class="form-control" /><br />
            <small class="form-text text-muted">This is the date where your loan will be approved.</small>
            <span asp-validation-summary="All"></span>
        </div>
        <div class="form-group">
            <label> Due Date: </label>
            <input type="date" id="dpDateDue" name="lc.loanContract.LoanPaymentDue" class="form-control" /><br />
            <small class="form-text text-muted">Date where you expected to pay them all.</small>
            <span asp-validation-summary="All"></span>
        </div>
    </div><br />
    <div class="form-group">
        <label>Loan Amount</label>
        <input required placeholder="Enter Amount (must be number)" name="lc.loanContract.LoanAmount" class="form-control" type="number"/>
        <small class="form-text text-muted">Input the amount you want to loan.</small>
        <span asp-validation-summary="All"></span>
    </div>
    <div class="form-control" style="height: 100%">
        <label>Terms and Condition</label><br />
        <input required type="checkbox" name="lc.loanContract.isAcceptTac"/>
        <small class="form-text text-muted"><b>I Agree, Read and Accept the terms terms and condition. </b><br />
            PEMCO Loan is an online peer to peer loans community that connects people with money to lend to people who need to borrow money. Lending Hub works in a controlled and regulated environment that allows members to interact anonymously (from each other). To make sure that a secure and safe community is maintained we have developed these terms and conditions of use to assist all members. These terms and conditions explain what you can expect from us, what we expect from you, and what members can expect from each other and these terms and conditions will apply to you whenever you browse, transact or interact on the site.
        </small>
        <span asp-validation-summary="All"></span>
    </div><br />
    <div class="form-control-static">
        <button type="submit" class="btn btn-primary"><b>Apply</b></button>
    </div>
    
</form>

现在一切都在视图中设置,我现在唯一遇到的问题是从我在代码中定义的ModelLoan.loanContract 插入数据:

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> SaveLoanContract(ModelLoan lc)
    { 
        if (ModelState.IsValid)
        {
            await _Context.LoanContract.AddAsync(lc.loanContract);
            await _Context.SaveChangesAsync();

            return RedirectToAction("Index");
        }
        return View(lc.loanContract);
    }

假设我的代码有什么问题?我错过了一件小事,但我不知道在哪里。你们能帮我解决这个问题吗?谢谢!

更新: 这是当我使用asp-action = "SaveLoanContract" 时发生的异常,因为它与索引本身相关联。

InvalidOperationException:未找到视图“SaveLoanContract”。搜索了以下位置: /Views/Loan/SaveLoanContract.cshtml /Views/Shared/SaveLoanContract.cshtml

但是当我更改asp-action = "Index"

InvalidOperationException:传递到 ViewDataDictionary 的模型项的类型为“PEMCOLoan.DAL.Entities.Models.LoanContract”,但此 ViewDataDictionary 实例需要“prjPEMCOLoan.Models.ModelLoan”类型的模型项。

如果我错过了什么,请告诉我。

【问题讨论】:

  • 您能提供异常详情吗?可能 ModelLoan 缺少属性 [FromBody],您是否检查过 lc 是一个有效实例并且 lc.loanContract 有值?
  • 您好,问题已更新。您可以立即查看。
  • 请检查控制器中方法的路由,路由表似乎有问题
  • @H. Herzl hmp... 好的,但你能给我一个代码吗?抱歉我现在还在学习asp.net core..不太熟悉。

标签: asp.net-core entity-framework-core


【解决方案1】:

使用 ASP.NET Core,您将拥有新标签 asp-for。将您的视图更改为:

@model prjPEMCOLoan.Models.ModelLoan

<form asp-controller="Loan" asp-action="SaveLoanContract" role="form" method="post" style="padding-top: 2em;">
<h2>Loan Application</h2>
<div class="form-group">
    <label>Select Employee</label>
    <select class="form-control" asp-for="loanContract.EmployeeId" asp-items="@Model.employees"></select>
    <small class="form-text text-muted">Select the specific employee. If employee name is not on the list then you register the employee <a asp-controller="Employee" asp-action="Index">here</a>.</small>
    <span asp-validation-summary="All"></span>
</div>

<div class="form-group">
    <label>Select Collector</label>
    <select class="form-control" asp-for="loanContract.CollectorId" asp-items="@Model.collectors"></select>
    <small class="form-text text-muted">Collector will be the one to check your loan status in this system.  He/She will be the responsible for accepting/rejecting your loan applied.</small>
    <span asp-validation-summary="All"></span>
</div>

<div class="form-group">
    <label>Select Loan Type</label>
    <select class="form-control" asp-for="loanContract.LoanTypeId" asp-items="@Model.loanTypes"></select>
    <small class="form-text text-muted">Choose your desired loan type you want to apply.</small>
    <span asp-validation-summary="All"></span>
</div>

<div class="form-group">
    <label>Status</label>
    <select class="form-control" asp-for="loanContract.LoanStatusId" asp-items="@Model.loanStatus" disabled></select>
    <small class="form-text text-muted">Upon registration to this loan you are set to pending status as default to check your loan by the collectors.</small>
    <span asp-validation-summary="All"></span>
</div>

<div class="form-group">
    <label>Status</label>
    <select class="form-control" asp-for="loanContract.LoanFrequencyId" asp-items="@Model.loanFrequency" disabled></select>
    <small class="form-text text-muted">Upon registration to this loan you are set to a <b>Biweekly</b> because your payroll mostly computed and deducted every Biweekly day of the month.</small>
    <span asp-validation-summary="All"></span>
</div>

<div class="form-inline">
    <div class="form-group">
        <label> Date Applied: </label><span> </span>
        <input disabled type="date" asp-for="loanContract.LoanDateStart" id="dpDateNow" class="form-control" /><br />
        <small class="form-text text-muted">This is the date you applied.</small>
        <span asp-validation-summary="All"></span>
    </div>
    <div class="form-group">
        <label> Date Approved: </label><span> </span>
        <input type="date" id="dpDateApproved" asp-for="loanContract.LoanDateEnd" class="form-control" /><br />
        <small class="form-text text-muted">This is the date where your loan will be approved.</small>
        <span asp-validation-summary="All"></span>
    </div>
    <div class="form-group">
        <label> Due Date: </label>
        <input type="date" id="dpDateDue" asp-for="loanContract.LoanPaymentDue" class="form-control" /><br />
        <small class="form-text text-muted">Date where you expected to pay them all.</small>
        <span asp-validation-summary="All"></span>
    </div>
</div><br />
<div class="form-group">
    <label>Loan Amount</label>
    <input required placeholder="Enter Amount (must be number)" asp-for="loanContract.LoanAmount" class="form-control" type="number"/>
    <small class="form-text text-muted">Input the amount you want to loan.</small>
    <span asp-validation-summary="All"></span>
</div>
<div class="form-control" style="height: 100%">
    <label>Terms and Condition</label><br />
    <input required type="checkbox" asp-for="loanContract.isAcceptTac"/>
    <small class="form-text text-muted"><b>I Agree, Read and Accept the terms terms and condition. </b><br />
        PEMCO Loan is an online peer to peer loans community that connects people with money to lend to people who need to borrow money. Lending Hub works in a controlled and regulated environment that allows members to interact anonymously (from each other). To make sure that a secure and safe community is maintained we have developed these terms and conditions of use to assist all members. These terms and conditions explain what you can expect from us, what we expect from you, and what members can expect from each other and these terms and conditions will apply to you whenever you browse, transact or interact on the site.
    </small>
    <span asp-validation-summary="All"></span>
</div><br />
<div class="form-control-static">
    <button type="submit" class="btn btn-primary"><b>Apply</b></button>
</div>

您的控制器方法:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SaveLoanContract(ModelLoan lc)
{ 
    if (ModelState.IsValid)
    {
        await _Context.LoanContract.AddAsync(lc.loanContract);
        await _Context.SaveChangesAsync();

        return RedirectToAction("Index");
    }

    // Get the list data again and populate the entire model
    lc.employees = new SelectList(lstEmployee, "Id", "Value");
    lc.collectors = new SelectList(lstCollector, "Id", "Value");
    // and so on

    return View("Index", lc); // also it may be required to specify the full path for the view like ~/Views/Home/Index.cshtml
}

PS:这&lt;span asp-validation-summary="All"&gt;&lt;/span&gt; 部分代码不需要在每个输入上。您可以在输入之前放置一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 2018-02-07
    • 2018-02-12
    • 2020-05-16
    • 1970-01-01
    相关资源
    最近更新 更多