2

my view model is a viewmodel which has two models,

  publish class ViewModel
  { 
  public Student StudentModel{get;set;}
  public Teacher TeacherModel {get;set;}
  }

I has two forms called StudentForm and TeacherForm,Which binding StudentModel and TeacherModel respectively.Now I fill in some data in StudentForm and submit it. I use ModelState.Clear(); to clear my StudentForm data ,but It seems not only clear the data of the StudentForm but also the TeacherForm,How can I only clear the data of the StudentForm?

4

5 回答 5

8

缩短,你可以做

foreach (var key in ModelState.Keys.Where(m => m.StartsWith("StudentModel")).ToList())
                ModelState.Remove(key);
于 2013-09-06T20:18:37.607 回答
2

在这种情况下,您将不得不StudentModel从您的ModelStateie中删除每个属性

句法:

ModelState.Remove("PropertyName"); 

例子:

ModelState.Remove("Id"); 
ModelState.Remove("Name"); 
ModelState.Remove("Marks"); 

编辑:对于两个中的特定模型属性

ModelState.Remove("StudentModel.Name"); 
于 2013-09-06T15:37:52.820 回答
1

ModelState.Remove("StudentForm"),这里是 MSDN 链接, http: //msdn.microsoft.com/en-us/library/dd470162%28v=vs.108%29.aspx

于 2013-09-08T08:27:32.697 回答
0

从操作返回模型时,您可以重新初始化学生对象

例如:

    [HttpPost]
    public ActionResult ActionName(ViewModel model)
    {
       model.StudentModel = new StudentModel();
       return View(model);
    }
于 2013-09-06T15:41:05.597 回答
0

注意:ModelState Key 包含您的 ViewModel 名称,例如:

ModelState.Remove("YourViewModelName.YourPropertyName");

于 2021-08-26T10:27:55.397 回答