[英]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.