问题描述
在插入之前,我想检查记录是否已插入。
这是我的查看模型,模型和操作
public class VMUsers
{
[Key]
[Column(tblUsers.Id)]
public int Id {get;组; }
public MVCLearning.Models.Users InsertUser {get;组; }
public MVCLearning.Models.UserDetails InsertUserDetails {get;组;
}
模型
[Table(tblUsers)]
public class Users
{
[Key]
public int Id {get;组; }
[Remote(CheckUserName,Users,ErrorMessage =Fullname不存在)]
public string FullName {get;组; }
public string LastName {get;组;
}
行动
public JsonResult CheckUserName(string FullName)
{
返回Json(!db.Users.Any(x => x.FullName == FullName),JsonRequestBehavior。 AllowGet);
}
创建动作
public ActionResult Create(VMUsers vmModel)
{
if(ModelState.IsValid)
{
CheckUserName(vmModel.InsertUser.FullName);
var user = new Users()
{
FullName = vmModel.InsertUser.FullName,
LastName = vmModel.InsertUser.LastName
};
//插入父表以获取我们将在Child表中使用的Id。
db.Users.Add(user);
db.SaveChanges();
}
return View(vmModel);
}
现在我要检查现有记录,如果存在,则出现错误消息应该在View上显示,如果它的新记录应该被插入如何一起做两件事。
查看
@model MVCLearning.Models.VMUsers
@ {
ViewBag.Title =创建;
}
< h2>创建< / h2>
@using(Html.BeginForm())
{
@ Html.AntiForgeryToken()
< div class =form-horizontal >
< h4> Users< / h4>
< hr />
@ Html.ValidationSummary(true)
@ Html.ActionLink(转到索引,索引)
< div class =form-group>
@ Html.LabelFor(model => model.InsertUser.FullName,new {@class =control-label col-md-2})
< div class =col-md- 10\" >
@ Html.EditorFor(model => model.InsertUser.FullName)
@ Html.ValidationMessageFor(model => model.InsertUser.FullName)
< / div>
< / div>
< div class =form-group>
@ Html.LabelFor(model => model.InsertUser.LastName,new {@class =control-label col-md-2})
< div class =col-md- 10\" >
@ Html.EditorFor(model => model.InsertUser.LastName)
@ Html.ValidationMessageFor(model => model.InsertUser.LastName)
< / div>
< / div>
< div class =form-group>
< div class =col-md-offset-2 col-md-10>
< input type =submitvalue =Createclass =btn btn-default/>
< / div>
< / div>
< / div>
}
< div>
@ Html.ActionLink(返回列表,索引)
< / div>
如果用户可以向ModelStateDictionary添加新错误存在于db中。
另外,看起来您的视图只发送FullName和LastName。在这种情况下,为什么不保持您的视图模型只具有这些属性,以便您的视图特定视图模型不会与您的实体模型紧密耦合。
public class CreateUserVM
{
[必需]
public string FullName {set; get;}
public string LastName {set; get;}
}
在你的GET操作中,确保你发送这个
public ActionResult Create()
{
return View(new CreateUserVM());
}
,您的视图将被强制输入到平面视图模型
@model CreateUserVM
@using(Html.BeginForm())
{
@ Html.ValidationSummary false)
< label>全名< / label>
@ Html.TextBoxFor(s => s.FullName)
< label>姓氏< / label>
@ Html.TextBoxFor(s => s.LastName)
< input type =submit/>
}
,您的HttpPost操作方法将为
public ActionResult Create(CreateUserVM model)
{
if(ModelState.IsValid)
{
var exists = db .Users.Any(x => x.FullName == model.FullName)
if(exists)
{
ModelState.AddModelError(string.Empty,Username exists);
return View(vmModel);
}
var user = new Users()
{
FullName = model.FullName,
LastName = model.LastName
};
//插入父表以获取我们将在Child表中使用的Id。
db.Users.Add(user);
db.SaveChanges();
return ReidrectToAction(Index); // PRG pattern
}
return View(vmModel);
}
I am inserting Full Name in table using Entity Framework.
Before inserting I want to check if the record is already inserted.
Here is my View model,model and action
public class VMUsers
{
[Key]
[Column("tblUsers.Id")]
public int Id { get; set; }
public MVCLearning.Models.Users InsertUser { get; set; }
public MVCLearning.Models.UserDetails InsertUserDetails { get; set; }
}
Model
[Table("tblUsers")]
public class Users
{
[Key]
public int Id { get; set; }
[Remote("CheckUserName","Users",ErrorMessage="Fullname doesn't exists")]
public string FullName { get; set; }
public string LastName { get; set; }
}
Action
public JsonResult CheckUserName(string FullName)
{
return Json(!db.Users.Any(x => x.FullName == FullName), JsonRequestBehavior.AllowGet);
}
Create Action
public ActionResult Create(VMUsers vmModel)
{
if (ModelState.IsValid)
{
CheckUserName(vmModel.InsertUser.FullName);
var user = new Users()
{
FullName = vmModel.InsertUser.FullName,
LastName = vmModel.InsertUser.LastName
};
//Inserting in Parent table to get the Id that we will used in Child table.
db.Users.Add(user);
db.SaveChanges();
}
return View(vmModel);
}
Now I want to check the existing record and if it exists then a error message should be shown on View and if its a new record it should be inserted how do I do two thing together.
View
@model MVCLearning.Models.VMUsers
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Users</h4>
<hr />
@Html.ValidationSummary(true)
@Html.ActionLink("Go to Index","index")
<div class="form-group">
@Html.LabelFor(model => model.InsertUser.FullName, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.InsertUser.FullName)
@Html.ValidationMessageFor(model => model.InsertUser.FullName)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.InsertUser.LastName, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.InsertUser.LastName)
@Html.ValidationMessageFor(model => model.InsertUser.LastName)
</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>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
You can add a new error to ModelStateDictionary if the user exist in the db.
Also, Looks like your view is only sending FullName and LastName. In that case, why not keep your view model to have only those properties so that your view specific-view model will not have any tight coupling with your entity models.
public class CreateUserVM
{
[Required]
public string FullName { set;get;}
public string LastName { set;get;}
}
And in your GET action make sure you are sending an object of this
public ActionResult Create()
{
return View(new CreateUserVM());
}
and your view will be strongly typed to our flat view model
@model CreateUserVM
@using(Html.BeginForm())
{
@Html.ValidationSummary(false)
<label>Full Name</label>
@Html.TextBoxFor(s=>s.FullName)
<label>Last Name</label>
@Html.TextBoxFor(s=>s.LastName)
<input type="submit" />
}
and your HttpPost action method will be
public ActionResult Create(CreateUserVM model)
{
if (ModelState.IsValid)
{
var exist= db.Users.Any(x => x.FullName == model.FullName)
if(exist)
{
ModelState.AddModelError(string.Empty, "Username exists");
return View(vmModel);
}
var user = new Users()
{
FullName = model.FullName,
LastName = model.LastName
};
//Inserting in Parent table to get the Id that we will used in Child table.
db.Users.Add(user);
db.SaveChanges();
return ReidrectToAction("Index"); //PRG pattern
}
return View(vmModel);
}
这篇关于用户名可用性并插入新用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!