在c#中实施验证后,我在更新记录时遇到问题 [英] After Implementing Validations in c#, I face problems in updating records

查看:62
本文介绍了在c#中实施验证后,我在更新记录时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Asp.net c#MVC中的一个项目上工作,我想使用数据注释在模型上实现验证,如下所示:

I'm working on a project in Asp.net c# MVC and I want to implement validations on a model using Data Annotations as follows:

public class MainRepository
{
   public int Id { get; set; }

   [Required]
   public int Category_Id { get; set; }

   [Required]
   public int Department_Id { get; set; }

   [Required]
   public DateTime Start_Date { get; set; }
}

我有一个控制器作为PM控制器,使用以下注册方法.

I have a controller as PM controller with the following Register Method.

public ActionResult Register()
{
       var event_category = _context.Event_Categories.ToList();
       var departments = _context.dept.ToList();
       var vm = new InsertEdit_ViewModel
       {
           evt_catgrss = event_category,
           depts = departmetns 
       };
       return View(vm);
   }

这是InsertEdit视图模型:

Here is the InsertEdit view Model:

public class InsertEdit_ViewModel
{
    public MainRepository Main_RP { get; set; }
    public List<Event_Categories> evt_catgrss { get; set; } 
    public List<Departments> depts { get; set; }
}
    public InsertEdit_ViewModel()
    {
        Main_RP = new MainRepository();
        evt_catgrss = new List<Event_Categories>();
        depts = new List<Departments>();
    }
}

这是Register Method的视图:

And this is the view for the Register Method:

@model Project.ViewModel.InsertEdit_ViewModel

@using (Html.BeginForm("Store", "PM", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
<div class="form-group">
    <label>Event Category</label><br/>
    @Html.DropDownListFor(a => a.Main_RP.Category_Id, new SelectList(Model.evt_catgrss, "Id", "type_of_event"), "Select a category", new { @class = "form-control btn-group dropdown-menu" })

    @Html.ValidationMessageFor(a=> a.Main_RP.Category_Id)
</div>

<div class="form-group">
    <label>Department</label>
    @Html.DropDownListFor(a => a.Main_RP.Department_Id, new SelectList(Model.depts, "Id", "DepartmentName"), "Select Employee Department", new { @class = "form-control btn-group dropdown-menu" })
    @Html.ValidationMessageFor(a=> a.Main_RP.Department_Id)
</div>

<div class="form-group">
    <label>Start Date</label>
    @Html.TextBoxFor(a => a.Main_RP.Start_Date, "Select Estimated Date of Start", new { @class = "form-control", @readonly = "readonly", @style = "cursor :default; background-color:#d4d4d4; font-size:11px;" })
    @Html.ValidationMessageFor(a=> a.Main_RP.Start_Date)
</div>


@Html.AntiForgeryToken();
<button class="btn btn-primary">Register</button>

}

最后这是PM控制器中的存储方法

And finally this is the Store Method within the PM controller

 [HttpPost]
 [ValidateAntiForgeryToken]
 public ActionResult Store(InsertEdit_ViewModel pmI)
 {
       if (!ModelState.IsValid)
       {

       var event_category = _context.Event_Categories.ToList();
       var departments = _context.dept.ToList();
       var vm = new InsertEdit_ViewModel
       {
           evt_catgrss = event_category,
           depts = departmetns 
       };


        return View("Register",vm);
        }
        _context.main_repz.Add(pmI.Main_RP);
        _context.SaveChanges();
        return RedirectToAction("Index", "SystemAdmin");
   }

现在直到这部分,包括验证在内,一切都可以正常工作.但是,每当我想使用另一种方法更改事件的日期时,都会遇到问题:

Now till this portion everything is working fine including the validations. But I'm facing issues whenever i want to change the date of an event with another method as follows:

这是PM Controller中的更改方法:

This is the Change Method within PM Controller:

public ActionResult Change(int? Id)
  {
      var EventDetails = _context.main_repz.Include(a => a.Event_Categories).SingleOrDefault(a => a.Id == Id);

      var vm = new ChangeVM()
      {
          Main_RP = EventDetails

      };

      return View(vm);
  }

这是ChangeVM(ViewModel)

This is the ChangeVM (ViewModel)

public class ChangeVM
{
  public MainRepository Main_RP { get; set; }
  public ChangeVM()
  {
     Main_RP = new MainRepository();
  }
}

这是更改方法的视图

@model FEFA_MIS.ViewModel.ChangeVM


@using (Html.BeginForm("ChangeDate", "PM", FormMethod.Post, new { enctype = "multipart/form-data" }))
{


<div class="form-group">
    <label>Select New Date</label>
    @Html.TextBoxFor(a => a.Main_RP.Start_Date, "{0:}", new { @class = "form-control"})
    @Html.ValidationMessageFor(a=> a.Main_RP.Start_Date)
</div>
@Html.AntiForgeryToken();
@Html.HiddenFor(a => a.Main_RP.Id);
<button class="btn btn-primary">Request</button>
}

最后这是PM控制器中的ChangeDate方法

And Finally this is the ChangeDate Method within PM controller

   [HttpPost]
   [ValidateAntiForgeryToken]
   public ActionResult ChangeDate(ChangeVM ap)
   {
       if (!ModelState.IsValid)
       {


           return View("Change",ap);
       }


       var item = _context.main_repz.Single(a => a.Id == ap.Main_RP.Id);
       item.Start_Date = ap.Main_RP.Start_Date;
       _context.SaveChanges();
       return RedirectToAction("Success", "PM");
   }

这一次它不能正常工作,

Now this time it is not working properly,

是的,如果我不选择新日期,它会给出确认消息,这很好.

Means, If I don’t select the new date It gives the validation message, which is perfectly fine.

但是,当我选择新日期时,它不会继续进行,因为我认为它也期望Category_Id和Department_Id,但是它们不再是ChangeDate方法的一部分,它们是用于注册的存储方法的一部分.

But when I select the new date It does not proceed as I think it is expecting the Category_Id and Department_Id too, but they are no longer part of ChangeDate Method, they were part of Store Method used for Registration.

如果我没记错的话,我认为模型中的所有三个[必填]字段都属于一个ModelState,但是无论如何我都被困在这里...

If i'm not mistaken, I think all of the three [Required] fields in the model, come under one ModelState, but anyhow I'm stuck here...

有什么解决方案?视图模型能否只访问特定的属性,而不是调用整个类(在我的情况下)?

what can be the solution? Can the View Models access only specific attributes instead of calling the whole class (as in my case)?

推荐答案

我不会在ChangeVM中使用MainRepository.这包括所有属性.相反,将您的ViewModels限制为仅在该视图中实际处理的那些字段.因此,只需将Id和Start_Date添加到ChangeVM,就可以了.

I would not use the MainRepository in your ChangeVM. This includes all properties. Instead, limit your ViewModels to only those fields, that you are actually processing in that view. So, just add Id and Start_Date to the ChangeVM, and you should be good.

这篇关于在c#中实施验证后,我在更新记录时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆