How to save client data first and reservation next, with a single onpostasync on .net 7 core and select2, when the client does not exists?

huangapple go评论84阅读模式
英文:

How to save client data first and reservation next, with a single onpostasync on .net 7 core and select2, when the client does not exists?

问题

  1. Explanation

该应用程序是一个使用Razor页面、.net7.0的Web API以及bootstrap5和select2 JavaScript构建的应用程序。通过一个表格和一个弹出按钮,当客户端存在时,我可以成功保存预订。问题出现在客户端不存在时。我点击选择框并输入姓名以查看是否存在。如果不存在,然后在<input>中复制输入的姓名,然后在提交时应该执行以下操作:

(a) 保存这个新客户,然后,

(b) 为这个客户保存预订。

我收到的错误:

SqlException: 无法将空值插入到列 'KliEm',表 'My_Data65.dbo.Clientss';该列不允许空值。插入操作失败。

  1. 问题

我做错了什么?

  1. 前端代码

以下是JavaScript代码:

<script>
    $("#original").keyup(function () {
        var textval = $("option:selected", this).val();
        $('input[name=originalcopy]').val(textval);
    });
    $("#original").change(function () {
        var textval = $("option:selected", this).val();
        $('input[name=originalcopy]').val(textval);
    });
</script>
  1. 后端代码

以下是OnPostCreateAsync方法的后端代码:

public async Task<IActionResult> OnPostCreateAsync()
{
    try
    {
        _context.Reservations.Add(Reservation);
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateException e)
    {
        e.ToString();
        _context.Clients.Add(Client);
        await _context.SaveChangesAsync();
        Reservation pp = new();
        pp.KliId = Client.CliId;
        pp.MyDate = Reservation.MyDate;
        pp.HourId = Reservation.HourId;
        _context.Reservations.Add(pp);
        await _context.SaveChangesAsync();
        return RedirectToPage("./Index1");
    }
    catch (Exception e)
    {  
        _ = e.ToString();
        return RedirectToPage("./Index");
    }
}
  1. 数据库代码

以下是数据库表的代码:

预订表:

CREATE TABLE [dbo].[Reservation](
    [ResId] [int] IDENTITY(1,1) NOT NULL,
    [MyDate] [date] NOT NULL,
    [HourId] [int] NOT NULL,
    [CliId] [int] NOT NULL,
 CONSTRAINT [PK__Reservation] PRIMARY KEY CLUSTERED 
(
    [ResId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Reservation]  WITH CHECK ADD FOREIGN KEY([CliId])
REFERENCES [dbo].[Clients] ([CliId])
GO
ALTER TABLE [dbo].[Reservation]  WITH CHECK ADD FOREIGN KEY([HourId])
REFERENCES [dbo].[ReservationHours] ([HourId])
GO

客户表:

CREATE TABLE [dbo].[Clients](
    [CliId] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](40) NOT NULL,
    [Tel] [char](20) NOT NULL,
    [Email] [nvarchar](40) NOT NULL,
 CONSTRAINT [PK__Clients] PRIMARY KEY CLUSTERED 
(
    [CliId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
  1. 添加新按钮

以下是"AddNew"按钮的代码:

<a href="#addreservationModal" class="btn btn-sm border-0"
   style="color:gray;font-size:70%;min-width: 150px;max-width: 150px;min-height:50px; text-align:right;" data-toggle="modal" data-bs-toggle="modal" 
   data-mydate="@DateTime.UtcNow.ToString("yyyy-MM-dd")" data-hourid="@ora.OraId"  id="btnCreate">
    +
</a>
英文:

1. Expaination

The app is a Razor pages, Web Api on .net7.0 with bootstrap5 and select2 javascript.

Through a table and a popup button, i can successfully save reservations, when the client exists.

The problem arises when the client does not exist.

I click on the select box write the name to see if it exists.

If it does not, then the name written, gets copied in an &lt;input&gt;, which, on post should:

(a) save this new client and then,

(b) save the reservation for this one client.

The error i get:

SqlException: Cannot insert the value NULL into column 'KliEm', table 'My_Data65.dbo.Clientss'; column does not allow nulls. INSERT fails.

2. Question

What am i doing wrong?

3. The frontend code

  &lt;div class=&quot;col-md-12&quot;&gt;
            &lt;!-- Modal --&gt;
            &lt;div class=&quot;modal fade&quot; id=&quot;addreservationModal&quot; tabindex=&quot;-1&quot; role=&quot;dialog&quot; aria-labelledby=&quot;addreservationModalLabel&quot; aria-hidden=&quot;true&quot;&gt;
                &lt;div class=&quot;modal-dialog&quot; role=&quot;document&quot; style=&quot;max-width:420px;&quot;&gt;
                    &lt;div class=&quot;modal-content&quot;&gt;
                        &lt;form id=&quot;Create&quot; method=&quot;post&quot; asp-page-handler=&quot;Create&quot;&gt;
                            &lt;div class=&quot;modal-body&quot;&gt;
                                &lt;div asp-validation-summary=&quot;ModelOnly&quot; class=&quot;text-danger&quot;&gt;&lt;/div&gt;

                                &lt;div class=&quot;form-group p-0&quot;&gt;
                                    &lt;label asp-for=&quot;Reservations.MyDate&quot; class=&quot;border-0 m-0&quot; style=&quot;max-height:20px;font-size:70%;&quot;&gt;Data&lt;/label&gt;
                                    &lt;input asp-for=&quot;Reservations.MyDate&quot; class=&quot;form-control fw-bold text-primary&quot; style=&quot;font-size:80%;&quot;
                                           id=&quot;mydate&quot; type=&quot;text&quot; readonly /&gt;
                                    &lt;span asp-validation-for=&quot;Reservations.MyDate&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;
                                &lt;/div&gt;
                                &lt;div class=&quot;form-group p-0&quot;&gt;
                                    &lt;label asp-for=&quot;Reservations.HourId&quot; class=&quot;border-0 m-0&quot; style=&quot;max-height:20px;font-size:70%;&quot;&gt;Ora...&lt;/label&gt;
                                            &lt;select asp-for=&quot;Reservations.HourId&quot; class=&quot;form-control fw-bold text-primary&quot;
                                                    id=&quot;HourIdpopup&quot; asp-items=&quot;ViewBag.HourId&quot; style=&quot;font-size:80%;&quot;&gt;
                                            &lt;/select&gt;
                                            &lt;span asp-validation-for=&quot;Reservations.PreOraId&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;
                                &lt;/div&gt;
                                &lt;div class=&quot;form-group p-0&quot;&gt;
                                    &lt;div class=&quot;row&quot;&gt;
                                        &lt;div class=&quot;col-12&quot;&gt;
                                            &lt;label asp-for=&quot;Reservations.CliId&quot; class=&quot;border-0 m-0&quot; style=&quot;max-height:20px;font-size:70%;&quot;&gt;Clients name&lt;/label&gt;
                                            &lt;br&gt;
                                            &lt;select asp-for=&quot;Reservations.CliId&quot; class=&quot;text-primary fw-bold form-select klient select2-container overflow-scroll&quot; asp-items=&quot;ViewBag.CliId&quot; name=&quot;original&quot; id=&quot;original&quot;
                                                    data-placeholder=&quot;--- Clients name ---&quot; style=&quot;font-size:80%;max-height:240px;&quot;&gt;
                                                &lt;option value=&quot;&quot;&gt;--- Clients name ---&lt;/option&gt;                                                   
                                            &lt;/select&gt;                                                
                                        &lt;/div&gt;
                                        &lt;div class=&quot;col-12&quot;&gt;
                                            &lt;input asp-for=&quot;Clients.KliEm&quot; class=&quot;form-control fw-bold text-primary&quot; name=&quot;originalcopy&quot; id=&quot;originalcopy&quot; style=&quot;font-size:80%;&quot;&gt; 
                                            &lt;input asp-for=&quot;Clients.Tel&quot; class=&quot;form-control fw-bold text-primary&quot; name=&quot;tel&quot; value=&quot;0&quot; style=&quot;font-size:80%;&quot;&gt;
                                            &lt;input asp-for=&quot;Clients.Email&quot; class=&quot;form-control fw-bold text-primary&quot; name=&quot;email&quot; value=&quot;a@a.a&quot; style=&quot;font-size:80%;&quot;&gt;
                                        &lt;/div&gt;
                                    &lt;/div&gt;
                                &lt;/div&gt;                                  
                                &lt;partial name=&quot;_BtnSavePartial&quot; /&gt;
                            &lt;/div&gt;
                        &lt;/form&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;

The javascript code

&lt;script&gt;
    $(&quot;#original&quot;).keyup(function () {
        var textval = $(&quot;:selected&quot;, this).val();
        $(&#39;input[name=originalcopy]&#39;).val(textval);
    });
    $(&quot;#original&quot;).change(function () {
        var textval = $(&quot;:selected&quot;, this).val();
        $(&#39;input[name=originalcopy]&#39;).val(textval);
    });
&lt;/script&gt;

4. The backend code

public async Task&lt;IActionResult&gt; OnPostCreateAsync()
    {
        try
        {
            _context.Reservations.Add(Reservation);
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateException e)
        {
            e.ToString();
            _context.Clients.Add(Client);
            await _context.SaveChangesAsync();
            Reservation pp = new();
            pp.KliId = Client.CliId;
            pp.MyDate = Reservation.MyDate;
            pp.HourId = Reservation.HourId;
            _context.Reservations.Add(pp);
            await _context.SaveChangesAsync();
            return RedirectToPage(&quot;./Index1&quot;);
        }
        catch (Exception e)
        {  
            _ = e.ToString();
            return RedirectToPage(&quot;./Index&quot;);
        }
    }


		        [BindProperty]
    public Clientss Clients { get; set; } = default!;
    [BindProperty]
    public Reservations Reservation { get; set; } = default!;

This is the database code:

  1. The reservation table

    CREATE TABLE [dbo].[Reservation](
    [ResId] [int] IDENTITY(1,1) NOT NULL,
    [MyDate] [date] NOT NULL,
    [HourId] [int] NOT NULL,
    [CliId] [int] NOT NULL,
    CONSTRAINT [PK__Reservation] PRIMARY KEY CLUSTERED
    (
    [ResId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    GO
    ALTER TABLE [dbo].[Reservation] WITH CHECK ADD FOREIGN KEY([CliId])
    REFERENCES [dbo].[Clients] ([CliId])
    GO
    ALTER TABLE [dbo].[Reservation] WITH CHECK ADD FOREIGN KEY([HourId])
    REFERENCES [dbo].[ReservationHours] ([HourId])
    GO

  2. The client table

    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[Clients](
    [CliId] [int] IDENTITY(1,1) NOT NULL,
    [Name] nvarchar NOT NULL,
    [Tel] char NOT NULL,
    [Email] nvarchar NOT NULL,
    CONSTRAINT [PK__Clients] PRIMARY KEY CLUSTERED
    (
    [CliId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    GO

This is the AddNew button

  &lt;a href=&quot;#addreservationModal&quot; class=&quot;btn btn-sm border-0&quot;
   style=&quot;color:gray;font-size:70%;min-width: 150px;max-width: 150px;min-height:50px; text-align:right;&quot; data-toggle=&quot;modal&quot; data-bs-toggle=&quot;modal&quot; 
   data-mydate=&quot;@DateTime.UtcNow.ToString(&quot;yyyy-MM-dd&quot;)&quot; data-hourid=&quot;@ora.OraId&quot;  id=&quot;btnCreate&quot;&gt;
	+
&lt;/a&gt;

答案1

得分: 2

我测试了你的前端代码,发现有一个问题。

你在第二个 select 标签和 KliEm 输入框中分别添加了 name=&quot;original&quot;name=&quot;originalcopy&quot;,这将导致后端无法填充相应的模型。你可以打开浏览器的开发者工具查看详细信息:

模型没有填充是因为参数名不正确。

你需要将 name 属性更改为模型中相应的名称。如果你不需要 name 属性,可以将其移除。

@*移除 name 属性*@
<select asp-for=&quot;Reservations.CliId&quot; class=&quot;text-primary fw-bold form-select klient select2-container overflow-scroll&quot; id=&quot;original&quot; asp-items=&quot;ViewBag.CliId&quot; data-placeholder=&quot;--- Clients name ---&quot; style=&quot;font-size:80%;max-height:240px;&quot;>
    <option value=&quot;&quot;>--- Clients name ---</option>
</select>  
@*......*@ 
@*更改 name 属性*@
<input asp-for=&quot;Clients.KliEm&quot; class=&quot;form-control fw-bold text-primary&quot; name=&quot;KliEm&quot; id=&quot;originalcopy&quot; style=&quot;font-size:80%;&quot;>
<input asp-for=&quot;Clients.Tel&quot; class=&quot;form-control fw-bold text-primary&quot; name=&quot;Tel&quot; value=&quot;0&quot; style=&quot;font-size:80%;&quot;>
<input asp-for=&quot;Clients.Email&quot; class=&quot;form-control fw-bold text-primary&quot; name=&quot;Email&quot; value=&quot;a@a.a&quot; style=&quot;font-size:80%;&quot;>

JavaScript 代码:

<script>
    $("#original").keyup(function () {
        var textval = $(":selected", this).val();
        $('input[name=KliEm]').val(textval);
    });
    $("#original").change(function () {
        var textval = $(":selected", this).val();
        $('input[name=KliEm]').val(textval);
    });
</script>

测试结果:

此外,我发现你的数据库表与实际模型不匹配,在提交表单时没有 Name 属性,即 Name=null,这也会导致相同的错误:Cannot insert the value NULL into column &#39;Name&#39;。请确保你的数据库表与模型一致。

英文:

I tested your front end code and it has a problem.

You have added name=&quot;original&quot; and name=&quot;originalcopy&quot; to the second select tag and KliEm input respectively, which will cause the backend to fail to populate the corresponding model. You can open the browser's developer tools to view the details:
How to save client data first and reservation next, with a single onpostasync on .net 7 core and select2, when the client does not exists?

How to save client data first and reservation next, with a single onpostasync on .net 7 core and select2, when the client does not exists?

How to save client data first and reservation next, with a single onpostasync on .net 7 core and select2, when the client does not exists?

The model is not populated due to a parameter with the wrong name.

You need to change the name attribute to the corresponding name in the model. If you don't need the name attribute, you can remove it.

@*Remove name attribute*@
&lt;select asp-for=&quot;Reservations.CliId&quot; class=&quot;text-primary fw-bold form-select klient select2-container overflow-scroll&quot; id=&quot;original&quot; asp-items=&quot;ViewBag.CliId&quot; data-placeholder=&quot;--- Clients name ---&quot; style=&quot;font-size:80%;max-height:240px;&quot;&gt;
    &lt;option value=&quot;&quot;&gt;--- Clients name ---&lt;/option&gt;
&lt;/select&gt;  
@*......*@ 
@*Change name attribute*@ 
&lt;input asp-for=&quot;Clients.KliEm&quot; class=&quot;form-control fw-bold text-primary&quot; name=&quot;KliEm&quot; id=&quot;originalcopy&quot; style=&quot;font-size:80%;&quot;&gt;
&lt;input asp-for=&quot;Clients.Tel&quot; class=&quot;form-control fw-bold text-primary&quot; name=&quot;Tel&quot; value=&quot;0&quot; style=&quot;font-size:80%;&quot;&gt;
&lt;input asp-for=&quot;Clients.Email&quot; class=&quot;form-control fw-bold text-primary&quot; name=&quot;Email&quot; value=&quot;a@a.a&quot; style=&quot;font-size:80%;&quot;&gt;

The javascript code:

&lt;script&gt;
    $(&quot;#original&quot;).keyup(function () {
        var textval = $(&quot;:selected&quot;, this).val();
        $(&#39;input[name=KliEm]&#39;).val(textval);
    });
    $(&quot;#original&quot;).change(function () {
        var textval = $(&quot;:selected&quot;, this).val();
        $(&#39;input[name=KliEm]&#39;).val(textval);
    });
&lt;/script&gt;

Test Result:
How to save client data first and reservation next, with a single onpostasync on .net 7 core and select2, when the client does not exists?

How to save client data first and reservation next, with a single onpostasync on .net 7 core and select2, when the client does not exists?

How to save client data first and reservation next, with a single onpostasync on .net 7 core and select2, when the client does not exists?

In addition, I found that your database table does not match the actual model, and you do not have the Name property when submitting the form, that is, Name=null, which will also cause the same error: Cannot insert the value NULL into column &#39;Name&#39;. Please make sure your database table is consistent with your model.

huangapple
  • 本文由 发表于 2023年7月11日 05:47:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76657537.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定