How to move to another View using a button in ASP MVC - html

I want to access to another page(View) by click a button. I try to write that in HTML code of my View using but it didn't work.
Shall I do it in Controller ? if yes how ? adding that I want to restrict the access only to the registred members.
this is what I tried :
<p>Sell your Car »</p>

If using a button is a alternative, you can also use this (though the suggestion provided by Ubiquitous Developers is also good):
Method 1
View
<form method="POST">
<input type="submit" name="sellCar" value="Sell your car" />
</form>
MVC Controller
public ActionResult Overview(string sellCar) {
if(!string.IsNullOrWhiteSpace(sellCar))
return RedirectToAction("SellYourCar");
return View();
}
public ActionResult SellYourCar() {
return View();
}
Method 2
View
#model CarMarketplace.Models.FormContent
<form method="POST">
<input type="submit" asp-for="Continue" value="Sell your car" />
</form>
MVC Controller
public ActionResult Overview(FormContent content) {
if(!string.IsNullOrWhiteSpace(content.Continue))
return RedirectToAction("SellYourCar");
return View();
}
public ActionResult SellYourCar() {
return View();
}
Model
public class FormContent {
public string Continue { get; set; }
}

Try this :
Sell your Car »
or
Sell your Car »

Related

Multibutton form doesn't map data back to textboxes .net core 1.1

Ok, so now I'm trying to learn .net core mcv and I'm having a problem mapping data from MySQL back to my form. When I make the form as a single text box with a single button, and the other fields outside the form (but on the same page), the mapping works fine. If I include all the fields within the form, the data is obtained but not displayed on the page. I have even gone so far as to code one of the multiple submit buttons as an update of the data. I use the first text box to get the item from the database, which it does (but does not map to the text-boxes), then in the second text box (which should have the existing data, but is empty) I put the information to update in the database, click on the submit button for that text box, and the database is updated (but the text boxes in the view remain blank).
My model:
using System;
namespace DbTest.Models
{
public class ProductInventory
{
public string Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
public int Field4 { get; set; }
}
}
my controller:
using System;
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;
using Microsoft.AspNetCore.Authorization;
using DbTest.Models;
namespace DbTest.Controllers
{
public class InventoryController : Controller
{
// [Authorize]
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult ProcessForm(string button, ProductInventory p)
{
IActionResult toDo = null;
if (button == "Button1")
{
toDo = GetItem(p);
}
if (button == "Button2")
{
toDo = UpdateField2(p);
}
if (button == "Button3")
{
toDo = UpdateField3(p);
}
if (button == "Button4")
{
toDo = UpdateField4(p);
}
return toDo;
}
// [HttpPost]
public IActionResult GetItem(ProductInventory p)
{
//CODE SNIP - DATABASE QUERY, IT ALL WORKS, SO WHY BOTHER YOU WITH THE DETAILS?
return View("Index", p);
}
public IActionResult UpdateField2(ProductInventory p)
{
//CODE SNIP - DATABASE UPDATE, ALL WORKS, NOTHING TO SEE HERE
return View("Index", p);
}
}
}
And finally, my view:
#model DbTest.Models.ProductInventory
#{
ViewData["Title"] = "Inventory Page";
}
#using (Html.BeginForm("ProcessForm", "Inventory", FormMethod.Post))
{
<div>
Search Item (Field 1):
#Html.TextBoxFor(model => model.Field1)
<input type="submit" name="button" value="Button1" />
</div>
<div>
Field 2:
#Html.TextBoxFor(model => model.Field2)
<input type="submit" name="button" value="Button2" />
</div>
<div>
Field 3:
#Html.TextBoxFor(model => model.Field3)
<input type="submit" name="button" value="Button3" />
</div>
<div>
Field 4:
#Html.TextBoxFor(model => model.Field4)
<input type="submit" name="button" value="Button4" />
</div>
}
To reiterate, if I close the form after Button1:
#using (Html.BeginForm("ProcessForm", "Inventory", FormMethod.Post))
{
<div>
Search Item (Field 1):
#Html.TextBoxFor(model => model.Field1)
<input type="submit" name="button" value="Button1" />
</div>
}
<div>
Field 2:
//etc.
the mapping works, but only the first field and button of the form work. With the form around all four fields and buttons, the mapping doesn't work, but the coding of the second button DOES update the database on clicking Button2.
Can someone explain what I've done wrong here?
Thanks!
At first, don't use html helpers in ASP.NET Core.They work but it is not best practice. Instead use tag helpers wherever possible. Furthermore, don't use your db models as view models.
Regarding your Index action: You forgot to pass a view model to your view.
In your ProcessForm action you instantiate IActionResult and then assign it with a (action) function. Don't do that. Instead use return RedirectToAction("ActionName");.
In your case I would handle the DB updates inside the ProcessForm action or in a function, which doesn't return IActionResult.
In conclusion, I can only recommend you to read the ASP.NET Core documentation and then ask again if you still don't get it to work. I recommend you to start with reading this.

Forwarding the partial view's details to HttpPost method of a controller when button in partial view is clicked

Whenever following HttpGet method in controller is called it generates a partial view.
Controller HttpGet Method
[HttpGet]
public ActionResult AddCredit(Guid creditBalanceId)
{
var newCredit = new AddCredits()
{
CreditBalanceId = creditBalanceId
};
return PartialView(newCredit);
}
View
#model AdminPortal.Areas.Customer.Models.ViewModels.AddCredits
#Html.HiddenFor(m=>m.CreditBalanceId)
<div class="input-small" id="credit">#Html.EditorFor(m=>m.CreditToAdd) </div>
#Html.ActionLink("Add","AddCredit", new {#class="btn"})
Whenever Add button is clicked in the partial view, I want it to be forwarded to HttpPost method of my controller with HiddenFor(CreditBalanceId) and CreditToAdd value
[HttpPost]
public ActionResult AddCredit(AddCredits credits)
{
_businessUnitRepository.AddCredits(credits);
Information("Credits Successfully added!");
return RedirectToAction("LicenseDetails");
}
Question
What changes do I need to make to my view so that when the button is clicked, i get forwarded to httppost method in controller with all the values?
Have you tried this?
#using(Html.BeginForm("Add", "AddCredit"))
{
#Html.HiddenFor(m=>m.CreditBalanceId)
<div class="input-small" id="credit">#Html.EditorFor(m=>m.CreditToAdd) </div>
<button type="submit" class="btn">Add Credit</button>
}
You could do it quite easily using something like Html.BeginForm and an type of submit. This link is a pretty good example MVC4 forms that save to entity framework models

How do I pass the id to the controller?

I have a textbox that like: <input type="text" id="10" name="SalesData" />
I'd like to pass the id back to the controller. Do I need to create a hidden textbox and store the id there? Or is there another way?
A hidden textbox would definitely be best for this scenario
<input type="hidden" id="SalesData" name="SalesData" value="10" />
and then in your post (or somewhere else like a viewmodel)
[HttpPost]
public ActionResult postedData(int SalesData){
//TODO: use SalesData
}
With a viewmodel:
public class SalesVM
{
public int SalesData { get; set; }
}
and then
[HttpPost]
public ActionResult ActionNameFromForm(SalesVM model){
//TODO: use model.SalesData
}
What exactly are you needing to do? Do you need to return both the id and value of the text box to the contoller? If so, i think the hidden field is the way to go.

Different behaviours for two different submit buttons?

I am trying to have two submit buttons in my form - one accepts meetings; the other declines them. They will both have different behaviours. How can I do is in my C# code?
The functionality I want is essentially
if(isPost) {
if(//accept button pressed(Request.Form[???]))
{
}
else
{
}
}
Here is my HTML :
<button name="accept" type="submit">Accept</button>
<div class="spacer"></div>
<button name="decline" type="submit">Decline</button>
<div class="spacer"></div>
Simple enough, but I cannot find a test for this on the Internet or in any documentation. Does anyone know what I would have for this ?
Give each button element the same name (in this example, 'SubmitButton') but a different value, then do a check for the different values in your server code, ie:
<button type="submit" name="SubmitButton" value="Accept">Accept</button>
<button type="submit" name="SubmitButton" value="Decline">Decline</button>
Then in your server code:
string buttonClicked = Request.Form["SubmitButton"]
if(buttonClicked == "Accept")
{
// Accept code
}
else if(buttonClicked == "Decline")
{
// Decline code
}
Be aware that this won't work on some earlier versions of IE though, and you may have to do a little javascript on the client prior to the post request being made.
As far as I remember, you have a controller action looking like this:
public ActionResult MyAction(string accept, string decline)
{
if (!string.IsNullOrEmpty(accept))
{
//do something
}
else
{
//do something else
}
}
Presuming you are using MVC3 you would do something like
#using (Html.BeginForm("Accept","Meeting"))
{
<input type="submit" value="Accept" />
}
#using (Html.BeginForm("Decline","Meeting"))
{
<input type="submit" value="Decline" />
}
You would then just have your accept and decline code in your Accept and Decline actions of your meeting controller respectively. No need for an if statement at all.
Example controller
public class MeetingController : Controller
{
[HttpPost]
public ActionResult Accept()
{
//Do accept stuff
return View();
}
[HttpPost]
public ActionResult Decline()
{
//Do decline stuff
return View();
}
}
Generally in the codebehind in c# you'd be looking for which button was clicked. You'd have an event handler for each button, and you code would react according to which button was clicked.
this.btnRejectAppointment.Click += new System.EventHandler(this.btnRejectAppointment_Click);
And then your method
private void btnRejectAppointment_Click(object sender, System.EventArgs e)
{
//code to reject appt.
}
And you'd have the SAME set for the other button.
ASP.NET Button control has OnClick event, so add different handler to every your button:
<asp:Button OnClick="MyHandler1" ... />
in code behind:
protected void MyHandler1(object sender, EventArgs args)
{ /* do stuff */ }
One of the possible solutions - use two buttons of type LinkButton but specify slightly different PostBackUrl:
<!-- Accept meeting button -->
<asp:LinkButton ID="acceptMeeting" runat="server"
PostBackUrl="MeetingsManager.aspx?Mode=Accept" />
<!-- Decline meeting button -->
<asp:LinkButton ID="declineMeeting" runat="server"
PostBackUrl="MeetingsManager.aspx?Mode=Decline" />
And in code behind:
public enum Mode
{
Unknown,
Accept,
Decline
}
protected void Page_Load(object sender, EventArgs args)
{
Mode currentMode = Mode.Unknown;
var rawMode = Request.QueryString["Mode"];
if (rawMode != null)
{
currentMode = (Mode)Enum.Parse(
typeof(Mode),
rawMode.ToString())
}
}

Missing case of value on input type="hidden"

I faced with missing case sensitive string value, how it can be fixed?
Example is following:
..
entity.Value = "Some Test Value";
entity.Name = "SomeTestName";
..
When I place it in View like following (I am using Razor),
<input type="hidden" name="#entity.Name" value="#entity.Value">
Then it will be rendered as following:
<input type="hidden" name="SomeTestName" value="some test value">
I used
<input type="hidden" name="#entity.Name" value="#Html.Raw(entity.Value)">
but result is the same.
So, its missing case. How it can be fixed?
Doesn't seem to be the case (status no-repro).
Model:
public class Entity
{
public string Name { get; set; }
public string Value { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var entity = new Entity();
entity.Value = "Some Test Value";
entity.Name = "SomeTestName";
return View(entity);
}
}
View:
#model Entity
<input type="hidden" name="#Model.Name" value="#Model.Value" />
Generated HTML:
<input type="hidden" name="SomeTestName" value="Some Test Value" />
See? Everything works perfectly fine. So we can draw only a single conclusion here: you haven't shown your full code allowing us to reproduce your problem rendering your question meaningless.