Passing a value from a text field to a controller

How can I get the value from the "EmailList" text box and send it to the controller? I always use webforms, and this is my first contact with mvc.

View:

@Html.TextBox("EmailList") @Html.Action("SendEmails") 

Controller:

  public ActionResult SendEmails() { // some operations on EmailList } 

EDIT


But what if I just need to open a simple "onclick" method? Not an actionresult. eg -

  public void SendEmails() { // some operations on EmailList } 
+7
source share
3 answers

So, to return the value to the controller, you need to first issue POST , so you need to configure your controller to POST :

 [HttpPost] public ActionResult SendEmails(string EmailList) { } 

Also note that I added the EmailList parameter, which is named exactly the same as the control on the form. Then we need to make sure that your HTML is configured correctly, so when you create the form control, follow these steps:

 @Html.BeginForm("SendEmails", "{ControllerNameHere}", FormMethod.Post) 

and then your text box, leave it alone, it should work fine.

+4
source

If you want to pass an EmailList method, then you should have a form surrounding the email text field

 @using (Html.BeginForm("","")) { @Html.TextBox("EmailList") <input type="submit" id="emailSubmit" value="Submit Email" /> } 

Then write a script to override the default behavior of the form

 <script type="text/javascript"> $(function () { $("form").submit(function (e) { e.preventDefault(); var emailValue = $("#EmailList").val(); $.ajax({ url: '/Home/SendEmails', data: { text: emailValue } }); }); }); </script> 

Now you can add a parameter to your method as follows:

 public void SendEmails(string text) { string email=text; //or you can look into the Request.Form or Request.Querystring } 

Hope this helps

+3
source

The model

 public class EmailSubmitModel { public string EmailList {get; set;} } 

In your controller

 public ActionResult SendEmails(EmailSubmitModel emailSubmitModel) { } 
+1
source

All Articles