使用ASP.NET Core和EF Core 1.1的模型插入数据

时间:2017-04-13 12:32:33

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

我对我的代码有疑问,

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

中的代码
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

现在这是查看:

&#13;
&#13;
@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>
&#13;
&#13;
&#13;

现在一切都在视图上设置我现在唯一有问题的是从我在我的代码中定义的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:视图&#39; SaveLoanContract&#39;没找到。搜索了以下位置:    /Views/Loan/SaveLoanContract.cshtml    /Views/Shared/SaveLoanContract.cshtml

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

  

InvalidOperationException:传递给ViewDataDictionary的模型项的类型为&#39; PEMCOLoan.DAL.Entities.Models.LoanContract&#39;,但此ViewDataDictionary实例需要类型为&#39; prjPEMCOLoan.Models的模型项。 ModelLoan&#39;

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

1 个答案:

答案 0 :(得分:0)

使用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:代码的<span asp-validation-summary="All"></span>部分不需要在每个输入上。您可以在输入之前放置一次。

相关问题