簡體   English   中英

如何使用 C# 使表單字段“DeviceId”唯一並在重復時拋出錯誤,ASP.NET MVC 和 Azure Cosmosdb?

[英]How to make form field “ DeviceId” unique and throw error if repeated, ASP.NET MVC and Azure Cosmosdb using C#?

我正在使用用 C# 編寫的 ASP.NET MVC web 應用程序。 我創建了一個表單來在 Azure Cosmosdb 集合中添加條目。 我想創建一個字段“DeviceId”作為唯一字段。 我正在為結果而苦苦掙扎。

Controller:

  [ActionName("Create")]
        public async Task<ActionResult> CreateAsync()
        {//DeviceTypeId dropdown
            List<SelectListItem> items = new List<SelectListItem>();

            items.Add(new SelectListItem { Text = "ChainZone", Value = "1" });
            items.Add(new SelectListItem { Text = "Particle", Value = "2" });
            items.Add(new SelectListItem { Text = "Raspberry Pi", Value = "3" });

            ViewBag.Type = items;

            //Device Stats dropdown
            List<SelectListItem> state = new List<SelectListItem>();

            state.Add(new SelectListItem { Text = "Non-Active", Value = "0" });
            state.Add(new SelectListItem { Text = "Active", Value = "1" });
            state.Add(new SelectListItem { Text = "In Production", Value = "2" });
            state.Add(new SelectListItem { Text = "In Maintenance", Value = "3" });
            state.Add(new SelectListItem { Text = "To Be Installed", Value = "4" });

            ViewBag.State = state;

            Device deviceModel = new Device();
            deviceModel.DeviceModelCollection = await DocumentDBRepository<Devicemodel>.GetDeviceModelAsync(d => d.Id != null);
            return View(deviceModel);
        }
[HttpPost]
        [ActionName("Create")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> CreateAsync([Bind(Include = "Id, DeviceId,Lat, Long,DeviceTypeId, DeviceModelId,EnvLog,SpeedLimit,ActivationSpeed,UserName,Password,PhoneNo,IMEI,Puk, SimPin,SpeedLog,GroupId,IPaddress,Name,Address,Status,Notes,DataTypeId,BomLocationId,BatInVoltage,SortValue,Sensors,LastContact,DisconnectedEvents")] Device item)//LastContact.Ping,LastContact.EnLog,LastContact.SpdLog,LastContact.Voltage,CreatedAt
        {
             var org = await DocumentDBRepository<Device>.GetDevicemapAsync(d => d.DeviceId == item.DeviceId);
            // var cond = 0;
            //if(org == item.DeviceId) { cond = 1; }

            if (ModelState.IsValid)
            {
                if(org == null)
                {
                    item.CreatedAt = DateTime.Now;
                    // item.LastContact.Ping = DateTime.Now;
                    await DocumentDBRepository<Device>.CreateDeviceAsync(item);
                    ViewBag.SuccessMsg = "Successfully added";
                    return RedirectToAction("Index", "DeviceMap");
                }
            }

            return View(item);
        }

Model:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using java.awt;
using System.ComponentModel.DataAnnotations;
using ServiceStack.DataAnnotations;
using Xunit.Sdk;

namespace WebApplication1.Models
{
    public class Device
    {
        [Unique]
        [JsonProperty(PropertyName = "DeviceId")]
        public string DeviceId { get; set; }
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }

        [JsonProperty(PropertyName = "Long")]
        public string Long { get; set; }

        [DisplayName("Devicemodel")]
        [JsonProperty(PropertyName = "DeviceModelId")]
        public int DeviceModelId { get; set; }

       [JsonProperty(PropertyName = "DeviceTypeId")]
        public int DeviceTypeId { get; set; }

        [JsonProperty(PropertyName = "IPaddress")]
        public string IPaddress { get; set; }
    }
}

看法:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Device</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        @Html.LabelFor(model => model.DeviceId, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">

            @Html.EditorFor(model => model.DeviceId, new { htmlAttributes = new { @class = "form-control", required = "required" } })
            @Html.ValidationMessageFor(model => model.DeviceId, "", new { @class = "text-danger" })
        </div>
    </div>
<div class="form-group">
        @Html.LabelFor(model => model.DeviceModelId, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.DeviceModelId,
           new SelectList(Model.DeviceModelCollection, "DeviceModelId", "DeviceModelCode"), "Select")
            @Html.ValidationMessageFor(model => model.DeviceModelId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.DeviceTypeId, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">

            @Html.DropDownListFor(model => model.DeviceTypeId, (List<SelectListItem>)ViewBag.Type, "Select")
            @Html.ValidationMessageFor(model => model.DeviceTypeId, "", new { @class = "text-danger" })
        </div>
    </div>
 <div class="form-group">
        @Html.LabelFor(model => model.Long, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Long, new { htmlAttributes = new { @class = "form-control", required = "required" } })
            @Html.ValidationMessageFor(model => model.Long, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.IPaddress, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.IPaddress, new { htmlAttributes = new { @class = "form-control", required = "required" } })
            @Html.ValidationMessageFor(model => model.IPaddress, "", new { @class = "text-danger" })
        </div>
    </div>
  <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

它不起作用,有三個下拉字段。 如果我根據 Controller 中的可用 ID 檢查 DeviceId,這些字段會出現以下錯誤。

值不能是 null。 參數名稱:items 描述:執行當前web請求時發生未處理的異常。 請查看堆棧跟蹤以獲取有關錯誤及其源自代碼的位置的更多信息。 異常詳細信息:System.ArgumentNullException:值不能為 null。 參數名稱:items

如果我刪除下拉字段一切正常。

請幫忙。

首先,您應該提及您的問題中提到的完整代碼(例如:DeviceModel.cs)。

其次,我懷疑錯誤正在出現:

@Html.DropDownListFor(model => model.DeviceTypeId, (List<SelectListItem>)ViewBag.Type, "Select")

這是因為您錯誤地提到了語法和/或不知何故它的值是null 我建議您將ViewBag.Type的值傳遞給 model 並像下面這樣使用它:

@Html.DropDownListFor(model => model.DeviceTypeId,
           new SelectList(Model.DeviceTypeCollection, "Select")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM