asp.net mvc-如何从视图向操作发布c#对象

本文关键字:操作 对象 视图 mvc- net asp | 更新日期: 2023-09-27 18:00:56

我有一个视图,它是通过调用一个操作来渲染的,我将一个视图模型传递给它,例如Vm1,然后填充一些下拉列表。

在这个视图中,我有一个"过滤器"部分,其中有一些文本框和一个"过滤"按钮,我想调用另一个操作来传递文本框的值,然后在div中的页面上部分呈现第二个视图。

因此,我已经完成了这项操作,我的操作如下所示,当单击"Filter"按钮时,ajax会调用它:

ActionResult ActionName (string inputText1, string inputText2, string inputText3, ...)

因为我有大约10个文本框,所以我想创建一个新的c#对象,并将该对象传递给这个操作,看起来像这样更简单:

ActionResult ActionName(MyActionFilters myFilters)

如何做到这一点?

asp.net mvc-如何从视图向操作发布c#对象

您可以拥有如下的模型

public class MyActionFilters
{
  public string Property1{get;set;}
  public string Property2{get;set;} 
  public string[] Property3{get;set;} 
  // add any number of properties....
}

您可以在Get-Action方法中传递空模型

ActionResult ActionName()
{
  MyActionFilters myEmptyActionFilers= new MyActionFilters();
  View(myEmptyActionFilers)
}

以形式

Html.TextBoxFor(model => model.Property1)
Html.TextBoxFor(model => model.Property2)

然后在post方法中,您可以访问表单中填充的模型我已经删除了以前的代码。新代码在编辑标签之后:(

编辑:抱歉我不在。这种功能可以使用AJAX轻松实现:(

如下所示。

[HttpPost]
PartialViewResult ActionName(MyActionFilters myActionFilers)// this is magic
{
  /*you can access the properties here like myActionFilers.Property1 and pass the 
    same object after any manipulation. Or if you decided have a model which contains 
    a variable to hold the search results as well. That is good.*/
   return PartialView(myActionFilers);
}

到目前为止,这是一个很好的例子。

不要忘记将jquery.unobtrusive-ajax.js脚本引用添加到您的视图中。如果没有,Ajax将不会产生影响。在给定的示例中,正如您所看到的,他已经在_Layout中完成了此操作。

PS:明智地选择将传递给视图的模型的属性,并享受Ajax!!

您需要将表单输入名称设置为ViewModel的属性,然后MVC将发挥一些神奇的作用。例如:

public class FormViewModel {
    public string input1 {get;set;}
    public string input2 {get;set;}
    // and so on
}

然后在你的行动:

public ActionResult FormPost(FormViewModel model) {
    // you'll have access to model.input1, model.input2, etc
}

最后,例如,在您想要创建的HTML表单上:

<input type="text" name="input1" />
<input type="text" name="input2" />

或者您可以使用Html.TextBoxFor(model => model.Input1),助手将正确命名所有内容。

输入标记的name属性应以对象名称("MyActionFilters"(为前缀

例如:

<input type="text" name="MyActionFilters.YOUR_PROPERTY_NAME" />

顺便说一句,您的操作方法应该用HttpPost属性进行注释。

[HttpPost]ActionResult ActionName(MyActionFilters myFilters(