Submitting form using controller method - asp.net-mvc

I'm trying to call a method from view, but it's not working! :(
My Controller code:
public class ProfessionalController : Controller
{
//
// GET: /Professional/
public ActionResult Index()
{
return View();
}
public ActionResult Sum(int nro1, int nro2)
{
var value = nro1 + nro2;
ViewBag.SumResult = value;
return View();
}
}
My views code:
Professional Index:
#{
ViewBag.Title = "Profissional";
}
<h2>Profissional</h2>
#using (Html.BeginForm("Professional", "Sum")) {
<input id="nro1" type="number" class="form-control marged_top" placeholder="Numero 1" />
<input id="nro2" type="number" class="form-control marged_top" placeholder="Numero 2" />
<button id="Sum" name="Sum" value="Sum" class="btn btn-default" type="button"
data-toggle="button">
Sum
</button>
}
Sum View:
#{
ViewBag.Title = "Sum";
}
<h2>Sum</h2>
#ViewBag.SumResult;
Doesn't occurs any error, just nothing happens when i click at Sum button.

Some issues:
You probably want your <button> with type="submit", otherwise the form will not be submitted, and the button will do nothing. See also: MDN - Button Type
Html.BeginForm("Professional", "Sum") should be Html.BeginForm("Sum", "Professional") - The controller is the second argument.
Html.BeginForm("Sum") would also work here, because this is the current controller.
The inputs should have name="nro1", not id - it is the name that is being submitted.
No need for semicolon after #ViewBag.SumResult (though that isn't a bug).
I'm not sure what data-toggle="button" is doing here.
Note that you are not "calling a Controller from a View" - you are submitting a form, which starts a new Controller-View cycle. Html.Action can do something similar, but that is not what you're trying to do here.
I'd also take this opportunity and recommend against using ViewBag - Use a strongly typed view model instead

Related

How to make a common POST method for multiple Submit buttons in a View

I have a view which load values and captures user input values. The page has multiple submit type buttons, and each has different purpose. Each button sends values to different sets of tables in the database.
For e.g.,
My query is to make a common form POST method for all the buttons.
My View is like:
#using (Html.BeginForm("CallAllocationSubmit", "Home", FormMethod.Post, new { id = "FrmCallAllocationSubmit", ReturnUrl = ViewBag.ReturnUrl }))
{
<table>
<tr>
<td>
<button class="btn btn-success btn-icon " type="submit" style="width:100px;" name="Allocate" >Allocate</button>
</td>
<td>
<button class="btn btn-primary btn-icon " type="submit" style="width:100px;" name="Defer" >Defer </button>
</td>
</tr>
</table>
}
My Controller is like :
[HttpPost]
public ActionResult CallAllocationSubmit(Allocation ObjAllocation, FormCollection frmCollection, string Allocate, string Defer)
{
try
{
if (!string.IsNullOrEmpty(Allocate))
{
// All code goes here
}
if (!string.IsNullOrEmpty(Defer))
{
// All Code goes here
}
return RedirectToAction("CallAllocation");
}
//catch block
}
I tried above method using if condition but the buttons ain't working, and not coming to the controller on clicking.
Please suggest how can I implement this functionality, or provide correction for my view and controller. Thanks!
For your scenario, you can use command parameter in your post action
That is,
<button class="btn btn-success btn-icon " type="submit" style="width:100px;" name="command" value="Allocate">Allocate</button>
set the name for all buttons as command and set value as your button action.
Now in your post action method, use string command as a parameter
[HttpPost]
public ActionResult CallAllocationSubmit(Allocation ObjAllocation, FormCollection frmCollection, string command)
{
try
{
if (command = "Allocate"))
{
// code for Allocate action
}
if (command = "Defer"))
{
// code for Defer action
}
return RedirectToAction("CallAllocation");
}
//catch block
}
Give the submit buttons the same name (not id) E.g. mySubmitButton. Set the value of each button to the value to retrieve (E.g. value="Allocate")
Then in the controller use
public ActionResult CallAllocationSubmit(Allocation ObjAllocation, FormCollection frmCollection, string mysubmitButton)
I would use ENUM for multiple buttons instead string actions, because you get intellisense that way:
public enum FilterButton{
Allocate = 1,
Defer = 2, //...
};
public ActionResult CallAllocationSubmit(Allocation ObjAllocation,FormCollection frmCollection, FilterButton buttonAction)
{
if(buttonAction == FilterButton.Allocate){
//...code
}
}
in View:
<button type="submit" name="buttonAction" value="#FilterButton.Allocate" ></button>

Passing form values from one controller view to another form on a different controllers view in asp MVC

Okay I'm new to MVC and trying to make me a webpage where I can transfer to small form box with a zip code and button, to quote page that will fill in the zip code part on the quote page.
My problem is I have two controllers a homeController that has a index view with a small form box. I need to pass the zip code to the QuoteController which has it's own view that populated with the new zip code.
the home controller input, indexview
#using (Html.BeginForm("Quote", "Quote"))
<p>Move From Zip:</p>
<input type="text" name="Zip"/><br />
<input type="submit" value="Next" name="next">
the quote form to receive the zip, on the quote controller, on the quote view
#Html.Label("Move From Zip ")<br />
#Html.TextBoxFor(m => m.MoveFromZip, "", new { maxlength = 5, #class = "short-textbox" })
what's the easiest way of doing this
In your Index view of HomeController, you can keep the form action to "Quote/Quote"
#using (Html.BeginForm("Quote", "Quote"))
{
<input type="text" name="Zip" />
<input type="submit" />
}
Create a view model for your Quote action method view in QuoteController
public class QuoteVm
{
public string Zip { set;get;
}
and in your QuoteController's Quote action method
[HttpPost]
public ActionResult Quote(QuoteVm model)
{
return View(model);
}
and your Quote view will be
#model QuoteVm
<p>Data passed(POSTED) from Index view</p>
#using(Html.BeginForm("QuoteSave","Quote"))
{
#Html.TextBoxFor(s=>s.Zip)
<input type="submit" />
}
Now for your form submit in this view, you need to have another HttpPost action method
[HttpPost]
public ActionResult QuoteSave(QuoteVm model)
{
// to do : Do something and return something
}

Pass Value of TextArea to Controller

I have the following code in a Partial View that is Rendered inside of another Partial View that is used as the _layout for all views in the project. There is a textarea for comments. I need to get the value of the Textarea to the Action Method in my controller. There is no ViewModel, so I don't know how to capture the contents.
<header>
<h4> Application Notes </h4>
#using (#Html.BeginForm("Comment", "LoanApplication"))
{
#Html.TextArea("Comment")
#*<textarea cols="100" rows="2" name="Comment" placeholder="Leave Comment ..."></textarea>*#
<input value="Add Comment" type="submit" />
}
</header>
The controller code is :
[HttpPost]
[Route("Comment")]
public async Task<ActionResult> Comment(string comment)
{
var loanApplicationServiceProxy = base.ServiceProvider.LoanApplicationServiceProxy;
var applicationComment = new LoanApplicationComment
{
};
await loanApplicationServiceProxy.PutLoanApplicationCommentAsync(applicationComment);
return View();
}
It seems as if it should be something easy, but I can't seem to figure it out. Thanks for any and all assistance.
Change
string comment
To
string Comment
One other thing to try is to receive a FormCollection instead.

Using webforms in MVC

I am learning MVC, following THIS tutorial. (link will take you directly to where i'm stuck). so far I have learnt, there's a controller for every view. Now i have to take input from user through web entry form as mentioned in tutorial. In my project, i have a controller named Default1 and i can run it as localhost:xyz/Default1/Index. it runs perfect.
Then i created a new Controller, named Default2 and bound it to some view to display some data, and it worked perfect as localhost:xyz/Default2/Displaycustomer. the customer information was static (hard coded). and controller is as:
public ViewResult DisplayCustomers()
{
Customer cobj = new Customer();
cobj.Code = "12";
cobj.Name = "Zeeshan";
cobj.Amount = 7000;
return View("DisplayCustomers",cobj);
}
Now i have to take input from User, regarding cutomer iformation, using html page as mentioned in tutorial. so i tried adding a new webform under view folder, and and modified my controller as:
[HttpPost]
public ViewResult DisplayCustomers()
{
Customer cobj = new Customer();
cobj.Code = Request.Form["Id"].ToString();
cobj.Name = Request.Form["Name"].ToString();
cobj.Amount = Convert.ToDouble(Request.Form["Amount"].ToString());
return View("DisplayCustomers",cobj);
}
My Question is: How can i make my project stared, so that it takes input first, and then displays it, using above controller? Did i add the webform at right location? What would be the link to run it? i tried localhost:xyz/Default2/entryform etc. but failed.
(in my entryform.aspx, i have mentioned form action="DisplayCustomer" )
It sounds like what you're missing is an action to just display the form. In otherwords, you just need an action to display a form. That form's POST action should reference your controller's DisplayCustomers action.
So in your controller code:
public class CustomerController : Controller
{
[HttpGet]
public ViewResult New()
{
return View("NewCustomer"); //Our view that contains the new customer form.
}
// Add your code for displaying customers below
}
And in your view, you have code like this
#using(Html.BeginForm("DisplayCustomers", "Customer")) {
<!-- Add your form controls here -->
}
Notice that I'm using the version of the BeginForm helper that specifies the action method and controller to call. This will write the form tag to post back to your DisplayCustomers action. Here is the equivalent HTML:
<form method="POST" action="/Customer/DisplayCustomers">
You would then access your form using the URL http://test.server/Customer/New.
This may not be the best example in the world...but this will at least get you rolling..
url would be:localhost:1234/Home/Customer
the controller
public ActionResult Customer()
{
return View();
}
[HttpPost]
public ActionResult Customer(FormCollection frm)
{
var name = frm["name"].ToString();
var address = frm["address"].ToString();
ViewBag.Name = name;
ViewBag.Address = address;
return View();
}
The view
<div>
#using (Html.BeginForm())
{
<input type="text" name="name" id="name" />
<input type="text" name="address" id="address"/>
<input type="submit" name="submit" value="submit" />
<input type="text" name="namedisplay" value='#ViewBag.Name'/>
<input type="text" name="addressdisplay" value='#ViewBag.Address'/>
}
</div>

string Model, passing value to controller issue

I have a ASP.NET Razor view which binds to string. Its very simple:
#model string
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
Hello, #Model
#using(Html.BeginForm())
{
<fieldset>
<label for="name" style="color: whitesmoke">Name:</label>
<input type="text" id="name"/>
<br/>
<input type="submit" value="Submit"/>
</fieldset>
}
And a simple controller:
[HttpGet]
public ActionResult Index()
{
object model = "foo";
return View(model);
}
private string name;
[HttpPost]
public ActionResult Index(string name)
{
return View();
}
When I push the submit button, the Index Post action result triggers, but the 'string name' parameter is null. Isn't Razor smart enough to automatically bind this property to my controller from the view because the input id matches the name of the param on the controller? If not, how do I bind this? I know with a model with properties I can use Html.HiddenFor(m => m.Foo), but since there's no properties, I don't know how to call this method properly.. I can set it properly calling Html.Hidden("name","foo"), but I don't know how to pass a the value here. I know I can use jquery call such as:
#Html.Hidden("name", "$('input[id=name]').val())");
This literally sends the jquery string to the controller as the value... I'm not sure what to do at this point. Thanks!
It is smart enough to bind the property, just give your input a name which matches with the action parameter:
<input type="text" id="name" name="name" />

Resources