calculate button pressed - retrieve rates from database - c#

I need to link to the database (finance rates) when someone enters a number in the text box and clicks calculate that it will pull the rates from the database and display the calculation below in a 'form message'. What should I put in the homecontroller/index to link the code to the database?
Index.aspx:
<td>You wish to convert:
<input type="text" name="amount" size="30" onblur="test_ifinteger(Index.amount,'amounts')"/>
<input type="submit" name="submitter" value="calculate" />
<tr><td colspan="2">That will produce:<%=ViewData["formmessage"] %></td></tr>
Home Controller:
public ActionResult Index()
{
financeInit();
if (Request.Params["submitter"] == "calculate")
calculatepressed();
return View();
public void calculatepressed()
{
.............
}

I would wrap your fields in a form like this:
<form action="Home" method="get">
<div>
You wish to convert:
<input type="text" name="amount" size="30" id="userValue" onblur=""test_ifinteger(Index.amount,'amounts')"/>
<input type="submit" name="userSubmit" />
<br />
That will produce:<%=ViewData["formmessage"] %>
</div>
</form>
Then have your controller something like this:
public ActionResult Index()
{
int value;
if (int.TryParse(Request.Params["amount"], out value))
{
ViewData["formmessage"] = calculatepressed(value);
}
return View();
}
private string calculatepressed(int value)
{
// Do your magic here and return the value you calculate
return value.ToString();
}
If this ever expands from a simple page you might want to consider changing the form action to a post and having two different methods handling the initial view of the home page and the a view for the results of the calculation.

Related

ASP net core MVC Call diferent actions under 1 form

I have my this in my controller:
[HttpPost]
public IActionResult Save(int IdentifikaceZ, ReklamaceModel model)
{
_db.Add(model);
_db.SaveChanges();
return RedirectToAction("MyMainView");
}
#using (Html.BeginForm("Save", "MyMainView", FormMethod.Post))
{
....
<input id="Insert" name="Insert" value="Insert" type="submit">
<input id="Edit" name="Edit" value="Edit" type="submit">
}
What I need is to Save/Edit info inside Form but I dont know how to tell server to decide which to do. So when I click button A or button B it does same thing. I need it to do seperate things but with same elemetns (elements inside form) Thanks for any help.
The buttons are named, and the way named buttons work is that only the one that is clicked makes it into the POST. As such, you can simply check for the presence of one key or the other in the form data:
if (Request.Form.ContainsKey("Insert"))
// do insert
if (Request.Form.ContainsKey("Edit"))
// do edit
First, add a property string ActionType to your ReklamaceMode model.
Then change your HTML to:
#using (Html.BeginForm("Save", "MyMainView", FormMethod.Post))
{
....
<input id="Insert" name="ActionType" value="Insert" type="submit">
<input id="Edit" name="ActionType" value="Edit" type="submit">
}
Now in your csharp code:
[HttpPost]
public IActionResult Save(int IdentifikaceZ, ReklamaceModel model)
{
// check model.ActionType, it will be either Insert or Edit
}
Add and update operations can be handled with one form and one method as well.
Add id as hidden form control, for existing records this field will have a value which is the relevant record id. For new records the value will be 0 by default (assuming id type is int).
#using (Html.BeginForm("Save", "MyMainView", FormMethod.Post))
{
....
#Html.HiddenFor(x => x.Id)
<input type="submit" name="submit" value="Save" />
}
on the backend check for the id value, if it is > 0 then you trigger update, otherwise it is a new record.
[HttpPost]
public IActionResult Save(int IdentifikaceZ, ReklamaceModel model)
{
if(model.Id > 0)
_db.Update(model);
else
_db.Add(model);
_db.SaveChanges();
return RedirectToAction("MyMainView");
}
That was a simplified implementation, in a real life project you need to do more control over the model before adding/updating. For example it is recommended to use an input model then bind the values to the db model...
if ou still need to use multiple submit buttons in one form to target different backend actions see Multiple Submit Buttons for standard form and ajax forms as well.
Here you can do like this:::
<form method="post" asp-controller="Home">
<a id="Insert" name="Insert" value="Insert" type="submit" asp-action="Delete" asp-route-DeleteID="#model.DeleteID"/>
<a id="Edit" name="Edit" value="Edit" type="submit" asp-action="Edit" asp-route-DeleteID="#model.EditID"/>
</form>
[HttpPost] public IActionResult Delete(int id) {
}
[HttpPost] public IActionResult Edit(int id) {
}

Different buttons in view to perform different operation in mvc

I am facing some problem in MVC
Inside view I have 2 buttons, one is for final submit and the other is for adding dynamic content to the view. Again both are used to post the form. I wanted to know how these would be used in controller.
example
If I click final submit, it will redirect to some view or any other operation and also if I click add button in the same view I want to return to the same view.
note: I am using both buttons to post the same action.
<input type="submit" name="actionBtn" value="add value" />
<input type="submit" name="actionBtn" value="finalsubmit" />
in Action
public ActionResult YourPostAction(string actionBtn)
{
if(actionBtn == "Add Value")
{
}
else if(actionBtn == "finalSubmit")
{
}
}
Another way if you want ( You have to play with name but different way)
#using (Html.BeginForm())
{
<input type="hidden" name="actionName" id="hdnAction" />
<input type="submit" value="test" name="actionBtn" onclick="setThis('test')" />
<input type="submit" value="test1" name="actionBtn" onclick="setThis('test1')"/>
}
<script language="javascript">
function setThis(obj) {
document.getElementById('hdnAction').value = obj;
}
</script>
In controller action
[HttpPost]
public ActionResult Index(string actionName)
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}

Having trouble in accessing posted form data (MVC)

How to access posted form data in action method and display in view
I'm creating an input wizard in MVC. There are two views, one for taking input from user and another for display the input data.
Here is the model's code:
public class Info
{
public int CustomerId { set; get; }
public double Price { set; get; }
public string name { set; get; }
}
}
Controller's Code-
public ActionResult FillCustomer()
{
return View();
}
public ActionResult DisplayCustomer(FormCollection frm)
{
Info info = new Info();
info.name = Convert.ToString( Request.Form["name"]);
info.Price = Convert.ToDouble(Request.Form["price"]);
info.CustomerId = Convert.ToInt32(Request.Form["customerid"]);
return View(info);
}
FillCustomer View's Code-
<form method="post" action="DisplayCustomer">
Name: <input type="text" id="name" /><br />
Price: <input type="text" id="price" /><br />
CustomerId: <input type="text" id="customerid" />
<br />
<input type="submit" id="btn1" />
</form>
</body>
</html>
DisplayCustomer View's Code-
<body>
<div>
Name is <%=Model.name %> and ID is <%=Model.CustomerId %>
<%if (Model.Price > 200)
{%>
Greater than 200
<%}
else %>
<%{%>Lesser than 200
<%} %>
</div>
</body>
</html>
I checked with debugger, controller is not getting posted data.
Your form's input elements should have a name attribute
<form method="post" action="DisplayCustomer">
Name: <input type="text" id="name" name="name" /><br />
Price: <input type="text" id="price" name="price" /><br />
CustomerId: <input type="text" id="customerid" name="customerid" />
<br />
<input type="submit" id="btn1" />
</form>
Now you will get form data as
Info info = new Info();
info.name = Convert.ToString( Request.Form["name"]);
info.Price = Convert.ToDouble(Request.Form["price"]);
info.CustomerId = Convert.ToInt32(Request.Form["customerid"]);
In controller, form data is received as key/value pairs. And keys are generaetd from name attributes.
You are using MVC so the parameter in DisplayCustomer method is your model passed from view, which is created implicitly by model binder. Change the type from FormCollection to Info class as following:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DisplayCustomer(Info model)
{
// you can now access to Info properties
}
This way values of Info object are populeted and I think this is what you are trying to accomplish.
I think you have missed to write a Attribute top of the DisplayCustomer function. Just write it, I hope it will work.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DisplayCustomer(FormCollection frm)
{
Info info = new Info();
info.name = Convert.ToString( Request.Form["name"]);
info.Price = Convert.ToDouble(Request.Form["price"]);
info.CustomerId = Convert.ToInt32(Request.Form["customerid"]);
return View(info);
}

Get html items from view to control

Still kind of new to MVC, so please bear with me. I'm trying to grab some dynamically generated HTML. In this case, list items in my notifyList. I plan on looping through each one in the controller and adding them as database entries. Any help is appreciated, thanks.
View
#model _BaseViewModel
// The form it's within...
#using (Html.BeginForm("Create", "Leaf", FormMethod.Post, new { id = "createForm" }))
<div class="editor-label bottom-area bottom-header">
Notification List:
</div>
<div class="editor-field bottom-area">
<ul id="notifyList"></ul>
</div>
Controller:
[HttpPost]
public ActionResult Create(_BaseViewModel model)
{
// Some loop here
// get html here
db.UserItems.AddObject(model.user);
db.SaveChanges();
//
return RedirectToAction("Index");
}
As far as I understood, you use jQuery to fetch <li/> elements into notifyList. What you need to do here is to generate a hidden input as well. Sample:
$("#btnAppend").click(function() {
for(var i = 0; i < 4; i++) {
var _val = "Foo " + i;
var $li = $("<li/>").text(_val);
var $hidden = #("<input/>").
attr("type", "hidden")
attr("name", "foo").
val(_val);
$hidden.appendTo($li);
$li.appendTo("#notifyList");
}
});
This code will generate following output inside your DOM:
<ul id="notifyList">
<li>Foo 0<input type="hidden" value="Foo 0" name="foo" /></li>
<li>Foo 1<input type="hidden" value="Foo 1" name="foo" /></li>
<li>Foo 2<input type="hidden" value="Foo 2" name="foo" /></li>
<li>Foo 3<input type="hidden" value="Foo 3" name="foo" /></li>
</ul>
When you make a http form post, you can grab the values by the below controller action implementation:
public ActionResult Index(string[] foo) {
foreach(var item in foo) {
//Work with each individual item
}
//continue your code
}
it doesn't work this way. html only exists in the view. the controller has no concept of html (not should it). data sent to the controller comes in 1 of types (GET, POST). there are others, but these are the main to.
get is typically associated with the querystring www.domain.com/mypage.aspx?key=value
where post is the input values from form
<form action="mypage.aspx" method="post">
<input name="key" value="value"/>
<input type="submit" value="click me"/>
</form>
So adding items to a html list won't provide any meaning to the controller. javascript and ajax provide more options on how the data gets sent to the server, but the data is sent, not the markup. and the data is sent as key value pairs.

Can I do a AcceptVerbs(HttpVerbs.Get/Post) and hijaxing on the same page MVC?

I am working with Hijaxing and I will have three buttons, Prev, Add, and Next. The hijaxing works with both the Add, and the Next button.
Prev button is set to 'onclick="history.back(-1)" '.
Add button is triggered by a '(Html.BeginForm("Add","Home"))' form with hijacking Jquery, which works fine.
Next button does does the same as the Add button. I would like the Next button to hit the [AcceptVerbs(HttpVerbs.Post)] in the Controller. Any suggestions?
CONTROLLER...
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string home)
{
return RedirectToAction("Index", "Home");
}
public string GetQuote(Index index)
{
if (isNullorEmpty(index.name) != "")
return "99";
else
return "Sorry";
}
ASPX...
<script type="text/javascript">
$(document).ready(function() {
$("form[action$='GetQuote']").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(response) {
$("#results").html(response);
});
return false;
});
});
</script>
<%using (Html.BeginForm("GetQuote", "Stocks")) {%>
<br />
<span id="results"></span>
<br />
<input id="txtSymbolName" name="name" type="text" />
<br />
<input type="button" name="getPrev" value="Prev" onclick="history.back(-1)" />
<input type="submit" value="Add" />
<input type="submit" name="home" value="Next" />
<% } %>
It looks like you're trying to have 2 submit buttons call different actions.
See here for the best ways to do it.

Categories

Resources