简体   繁体   中英

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

I am using an ASP.NET MVC web application written in C#. I create a form to add entries in Azure Cosmosdb collection. I want to create one field "DeviceId" as a unique field. I am struggling with result.

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; }
    }
}

View:

@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>
}

It's not working, with three dropdown fields. I get following error for those fields if I check DeviceId in against available Ids in Controller.

Value cannot be null. Parameter name: items Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentNullException: Value cannot be null. Parameter name: items

If I remove dropdown fields everything works fine.

Please help.

First of all , you should mention complete code which is mentioned in your problem (For ex: DeviceModel.cs).

Second , I suspect that the error is coming in line:

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

This is because you have mentioned the syntax incorrectly and/or somehow the value of it is null . I would suggest you to pass ViewBag.Type 's value in model and use it like below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM