Different buttons in view to perform different operation in mvc - c#

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();
}

Related

Calling ActionResult from PartialView never hits

Pretty new with MVC and going through a few tutorials. Have done the following:
Add a controller called CustomerController.
Add 2 methods
public ActionResult Render()
{
// Go to a third party WebAPI and get the results in a List
return PartialView("CustomerList", custList);
}
public ActionResult SomeTest()
{
Response.Redirect("Somepage");
}
I then add a page (LandingView.cshtml) and create a PartialView called CustomerList and add the below code to the LandingView page
#Html.Action("Render", "Customer")
When i view this page it renders the page with a list of customers. The HTML for the PartialView is
#using (Html.BeginForm("SomeTest", "Customer"))
{
<div class="container">
#foreach (var i in Model)
{
<a href="#i.Url">
<div class="product-grid__item__name">#i.Title</div><br />
<div class="product-grid__item__price">#i.Price.ToString("C")</div>
</a>
<input type="button" id="btnGo" value="Go" />
}
</div>
}
When i click the button it never hits the SomeTest method? In debug mode i have put a breakpoint on Render and SomeTest, Render hits on page load but when clicking Go it never hits the SomeTest method?
What am i missing here?
Set the 'type' attribute value of the input element to "submit" not "button". This will trigger the form submission on click.
<input type="submit" id="btnGo" value="Go" />
You may experience some build errors because the SomeTest() controller method is expecting a return value of type ActionResult.

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) {
}

How do i send data to asp.net controller so that it can return a view?

What I want to do is so simple, I'm still trying to learn ASP.NET with c# and MVC application but I'm just having a lot of difficulty getting a simple example to go through, then I can grow from it, here's how it goes: I have a simple html5 form that's method is GET, the type is text and I basically want to submit a text into my mvc controller, once my controller get's it, I want it to output that string 'worked' through HTML5, how do I do this?
summary: string 'worked' --> html form --> c# controller --> html (view?)
here's what I got for my 'view' (Search.cshtml)
<form action="Home/Search" method="get">
<input type="text" name="q" />
<input type="submit" value="Search" />
ok, so far so good, if I input 'worked' nothing is going to happen unless I add more code, here's c# (HomeController.cs):
public ActionResult Search(string q)
{
return this.View(q?); // so what exactly is View(q)? what is view returning? }
okay so this is where I am confused, does my string go through and become stored in 'q'? and if so, how do I get this thing to use HTML5 to output something like
<p> q </p> <!-- q = 'worked' -->
In your controller, you are calling the View(...) method incorrectly. The View(...) method expects the string parameter you're passing to be the path to the razor view you're trying to render.
A quick and simple way to pass the q variable from your controller to a view to be rendered is using ViewBag.
If you have a razor view named /Views/Search.cshtml you would do:
public class MyController : Controller
{
public ActionResult Search(string q)
{
ViewBag.Query = q;
return View("~/Views/Search.cshtml");
}
}
Then in /Views/Search.cshtml use it like this:
<p>#ViewBag.Query</p>
If you are using asp.net mvc, then please follow mvc pattern like this ..
View
#using (#Html.BeginForm("Search","Home",FormMethod.Post))
{
<b>Name : </b>
#Html.TextBox("searchTerm", null, new { #id = "txtSearch" })
<input type="submit" value="Search" />
}
Controller
[HttpPost]
public ActionResult Search(string searchTerm)
{
return View(searchTerm);
}
}
Search.cshtml
<form action="/Home/Search" method="get">
<input type="text" name="q" />
<input type="submit" value="Search" />
</form>
<p class='current-query'>#Model</p>
HomeController.cs
public ActionResult Search(string q)
{
return View((object)q); // return the model to the view (a string)
}

How to keep my model data when do GET>POST>REDIRECT to upload a file?

I want to create a register form using MVC which include a profile photo. I don't want to add record for people before completing the form (including profile photo upload). Also I want my UploadImage view and controller to be re-usable for many forms (not just this form). I pass three variables to my upload form through ActionLink: RedirectAction (RA), RedirectController (RC), and dataname and the procedure goes like this:
I store RA, RC, dataname in ViewBag, then put them in hidden <input> tags to be submitted when POSTing the file
// GET: UploadImage/Upload
public ActionResult Upload(string RA, string RC, string dataname)
{
ViewBag.RedirectAction = RA;
ViewBag.RedirectController = RC;
ViewBag.DataName = dataname;
return View();
}
Put these lines in my Upload.cshtml (View):
#using (Html.BeginForm("Upload", "UploadImage", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="hidden" name="RA" value="#ViewBag.RedirectAction" />
<input type="hidden" name="RC" value="#ViewBag.RedirectController" />
<input type="hidden" name="dataname" value="#ViewBag.DataName" />
<input type="submit" name="Submit" id="Submit" value="Upload" />
}
Store the filename in TempData with dataname as the Key and redirect to /RC/RA:
// POST: UploadImage/Upload/
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, string RA , string RC , string dataname)
{
var filepath = "C:/myfilename.jpg";
TempData.Add(dataname, filepath);
return RedirectToAction(RA,RC);
}
And get my filepath by utilizing TempData in my register form:
#if (TempData.Keys.Contains("MyData")) {
<div class="form-group">
<p>#TempData["MyData"].ToString()</p>
</div>}
The code works just fine, but the essential caveat is that I don't want other completed fields to get lost when redirected to the register form. How can I solve this problem ?
One option is to stick the data in the session. Another option would be to use a separate database table to hold in-progress registration data.

calculate button pressed - retrieve rates from database

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.

Categories

Resources