我想在将模型发送到我的操作之前验证一些字段。
这是我要验证的文本框
@Html.TextBoxFor(cModel => cModel.Value, new { id = "txtbLimit", @type = "int" })
@Html.ValidationMessageFor(cModel => cModel.Value)
和 ajax 帖子:
$.post('@Url.Action("AddUpdateConfigs")',
{QueueMonitorConfigurationsID: ident, QueueMonitorConfigTypeName: $('#ddlConfigTypeName').val(), Threshold:$('#ddlThreshold').val(), QueueMonitorValueTypeName:$('#ddlValueTypeName').val(), Location: $('#txtbLocation').val(), Value: $('#txtbLimit').val()},
function(data){
if (!data.Success){
alert(data.Description);
}
else{
//$('#gridView').load('/Storage/gvConfigurations');
$.get('@Url.Action("gvConfigurations", "Storage")',null,function(data){$('#gridView').html(data);},'html');
}
},'json');
它调用的函数:
public JsonResult AddUpdateConfigs(StorageConfigurationModel modelbind)
{
//Take the list of configurations
IEnumerable<StorageConfigurationModel> configList = (IEnumerable<StorageConfigurationModel>)Session["ConfigurationList"];
//Loop
foreach (StorageConfigurationModel configModel in configList)
{
//Is it a duplicated entry?
if ((configModel.QueueMonitorConfigTypeName == modelbind.QueueMonitorConfigTypeName) && (configModel.Location == modelbind.Location) && (configModel.QueueMonitorValueTypeName == modelbind.QueueMonitorValueTypeName) && (configModel.Threshold == modelbind.Threshold))
{
//Found duplicated entry
return Json(new { Success = false, Description = "Duplicate entry" });
}
}
//If not duplicated, add it to DB
try
{
if (modelbind.Location.StartsWith("\\"))
{
DirectoryInfo dir = new DirectoryInfo(modelbind.Location);
if (dir.Exists)
{
int finalValue = 0;
int pathInt = 0;
int valueTypeInt = 0;
if (modelbind.QueueMonitorConfigTypeName == PathType.Path)
pathInt = 1;
else
pathInt = 2;
switch (modelbind.QueueMonitorValueTypeName)
{
case UnitType.Percentage:
valueTypeInt = 1;
break;
case UnitType.MB:
valueTypeInt = 2;
break;
case UnitType.GB:
valueTypeInt = 3;
break;
case UnitType.TB:
valueTypeInt = 4;
break;
case UnitType.Files:
valueTypeInt = 5;
break;
}
if (modelbind.Threshold == ThresholdType.Upper)
finalValue = modelbind.Value;
else
finalValue = Convert.ToInt32("-" + modelbind.Value);
Boolean result = false;
result = DAL.queryAddUpdateConfig(modelbind.QueueMonitorConfigurationsID, pathInt, modelbind.Location, finalValue, valueTypeInt);
return Json(new { Success = result, Description = (result) ? ((modelbind.QueueMonitorConfigurationsID == -1) ? "New data inserted" : "Data updated") : "Error in Data types" });
}
else
{
return Json(new { Success = false, Description = "Location Path is not correct" });
}
}
else
{
return Json(new { Success = false, Description = "Location Path has to be UNC path" });
}
}
catch (Exception j)
{
return Json(new { Success = false, Description = "Error: " + j });
}
}
绑定模型但不进行验证是足够聪明的。如果我将一个字符串放在值(int)应该在的文本框中,它会将其转换为 0 并且不进行验证。
我还使用正则表达式验证了 Location ......再次不起作用。
有人看出有什么不对吗?谢谢
编辑:
我有:
@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "form" }))
{}
这在ajax帖子之前:
$('#form').validate();