Using an HTML button in MVC - c#

I feel a bit stupid asking this, but I just want to know how I can have a html button call a server site action on my controller.
For example lets say I have a Text Area and a submit button. The idea would be to click the submit button and the text in the text area would get submitted to the Database. Very simple stuff.
Thank you for the help!

in the aspx:
<%Html.BeginForm("Hello","Home",FormMethod.Post);%> <!--Name of method, name of controller, formmethod -->
<input type="text" id="userName" maxlength="50" name="userName"/>
<input id="Submit1" type="submit" value="Say Hello!" />
<%Html.EndForm();%>
<h2><%= Html.Encode(TempData["Message"]) %></h2>
In the Controller (HomeController in this example):
public ViewResult Hello(string userName) //note this variable is exactly what is the name of text input on page
{
//simple example, take input and pass back out
TempData["Message"] = "Hello, " + userName;
return View("Index",TempData);
}
EDIT: To address additional question about maintaining URL
One method to accomplish "staying in place" as far as your URL is to "overload" the Index method of your controller like below
[AcceptVerbs(HttpVerbs.Post)] //This is KEY <-----
public ActionResult Index(string userName)
{
//simple example, take input and pass back out
TempData["Message"] = "Hello, " + userName;
return View("Index",TempData);
}
Then in your Index.aspx change the Html.Begin Form like below, your just pointing to the default action now
<%Html.BeginForm("Index","Home",FormMethod.Post);%>
Since you are posting to the controller and not getting(the default index action) the version that is setup to AcceptVerb POST and take the userName string will run and your URL should be maintained

In the view's HTML, the text area and submit button would be part of a form, and that form's action attribute would point to '' and you'd put a part into the same controller that generated that view that checks for POST data. If there's POST data, you'd write it to the database.
The form would look something like this:
<form action='' method='post'>
<textarea name="text"></textarea>
<input type="submit" value="Submit"/>
</form>
In the POST, you'll see a variable with a key that matches the name attribute of the textarea (in this case, text). You can read it from there.
If you like, you can also change the action attribute on the form to a URL, in which case you'd write the part that checks the POST data in a controller that that URL points to.

Related

How to redirect to a View of another Controller from one Controller's View in ASP.NET MVC 4 Web Application

I am creating a Login page, where there'll be two buttons. One is submit type 'Sign-in' button and other is a redirecting button 'Sign-up' which gets the URL of a view of another controller.
This login page (View) belongs to Login Controller and the redirecting button should access the MemberSignup View of the SignUp Controller.
<p>
<input type="button" value="Sign Up" class="btn" onclick= "document.location.href='SignUp/MemberSignUp'";/>
</p>
while running the above code it is executing with the URL: ~/Login/SignUp/MemberSignUp. Thus giving an error as the Login controller should not be included.
Another aproach if you don't want to rely on JavaScript for links on buttons, you can simply use an anchor and style it, making it look like a button, using css.
Your button text
Just add a "/" before your url to indicate that the path is absolute, not relative : document.location.href='/SignUp/MemberSignUp'
Or use the razor method to generate the url (best method) : #Url.Action("MemberSignup", "SignUp");
One method is just to point to the correct URL, example below;
<p>
<a href="/SignUp/MemberSignUp" >Sign Up</a>
<p>
or as mentioned below you can use an ActionResult.
However the issue you're having with your code is that you're missing the leading / from your redirect.
Add the following helper method to your view:
#Html.ActionLink("Your link text here", "MemberSignUp", "SignUp")
Moreover if you want some styling you can type:
#Html.ActionLink("Your link text here", "MemberSignUp", "SignUp", null, new{ #class="your-class" })
You can use as ActionLink as below:
#Html.ActionLink("Sign Up", "MemberSignUp", "SignUp", null, new { #class="your-class" } })

Pass Value from View to Controller - MVC

i have a list of thumbnails for the user can select one of the image.
onclick on the thumbnail open a larger image into a form.
What im trying to do now is send the id of the image selected to my controller.
Note: im using MVC 4.
how can i do that?
someone can help with this pls?
Thanks in advance:
Here is my code:
#foreach (var p in ViewBag.Images)
{
<li>
<a href="~/Files/#p.Name" onclick="swap(this); return false;">
<img src="~/Files/#p.Name"/>
</a>
</li>
}
when selected is going this img tag in my form:
<img id="main" src="" >
using this javascript for this event:
function swap(image) {
document.getElementById("main").src = image.href;
}
what i have to do now?
i trying with <input type="hidden" name="Img_Id" value="Viewbag.??????"/>
to pass this value to my controller??
First, some terminology help: You can't pass a value from the view to the controller action, the view is rendered after the controller action completes.
What you want to do is pass data from the client (web browser) to a controller action, using form fields.
In your javascript swap method, you could set the value of the Img_Id field to be the value for the selected image. When the form is submitted, the Img_Id will be posted as form data, and can be accepted as a parameter in the action.
You can use JQuery (or something else) to perform the client side actions.
Here's an example (not tested though!):
First add the ID as a data attribute on the element:
<a href="~/Files/#p.Name" data-id="#p.ID" onclick="swap(this); return false;">
Then some javascript to save that to form (using jquery here):
function swap(image) {
document.getElementById("main").src = image.href;
$("input[name='Img_Id']").val($(image).data("id"));
}
To pass a value back to your controller, you either need to submit a form, or else make an AJAX request to your controller.
In the first case, you'd need to update the value of your hidden field with javascript, and then either wait for the user to submit the form, or trigger a submit through javascript depending on what your needs are.
If you want to do an ajax request, it would be more or less the same thing, but you don't need a hidden field to store the value.
You could use jQuery in your swap function. See here for the official documentation.
If you chose to use this approach, and assuming you place your JavaScript in a separate file, then make sure you get the path for the action and controller and pass that in too.
var url = #Url.Action("Index","Home");
Therefore you may call: onclick="swap(this.id, url)"

Pass Value from Button back to C# Controller from ASP.NET MVC 3 Razor Page

I have two buttons on my cshtml page - Agree and Disagree - how can I easily pass back there values to my Controller so I can make a decision to either take them to Homepage or Log them back out.
So on my cshtml page I have...
<input type="button" name='Agree' value="I Agree"
onclick="location.href='#Url.Action("DoAccept", "Home")'" />
<input type="button" name='Delete' value="I Disagree"
onclick="location.href='#Url.Action("DoAccept", "Home")'" />
So In my Home Controller then I have a DoAccept method as below:
public ActionResult DoAcceptTC()
{
//if( buttom clicked was Agree)
return RedirectToAction(VIEW_HOMEPAGE);
//else
//return Logout page..
}
So My question is how can I easily get a value back to the controller method?
There's no much point in using inputs without html form hosting them. You could use form, or simple links
//view
#using(Html.BeginForm("DoAccept"))
{
<button name="decision" value="agree">I Agree</button>
<button name="decision" value="disagree">I disagree</button>
}
//controller
public ActionResult DoAcceptTC(string decision)
{
//decision == "agree"
}
You must send paramaters along with Url.Action to the controller so that you can be able to perform your actions easily. Below link may help you.
Url.Action with params

mvc 3 - Automatically going to HttpPost

I have an action as follows:
public ActionResult ChangeFeeCheck(string id)
{
ViewBag.id = id;
return View();
}
on my View, I have the following:
#{
ViewBag.Title = "CreateList";
}
Please enter first name <br /><br />
#using (Html.BeginForm())
{
#Html.Textbox("firstname")
<input type="button" id="SaveChanges" value="Save" />
}
When I click on the button, I was expecting it to to the following
[HttpPost]
public ActionResult ChangeFeeCheck(string firstname)
{
.....
}
I am not sure when MVC will automatically go to the HttpPost or if I when need to manually have it there. In the above, it does not go there directly. I have to use the
window.location.href
and pass the url of the controller/action.
Meaning, isn't the default for
Html.BeginForm()
The HttpPost(same name as the HttpGet)
You need the button to be a submit button:
Change:
<input type="button" id="SaveChanges" value="Save" />
^^^^^^
To:
<input type="submit" id="SaveChanges" value="Save" />
^^^^^^
If you are following "Convention over configuration" rule over here, then the view you have created here must be for ChangeFeeCheck action, and ChangeFeeCheck here looks like will make compiler confused as no overload, same name, same signatures.
and then when method for form is get it would go to the first one, while if method for form is POST, it will call the one decorated with [HttpPost]
And because you are using submit button and by default HTML form generated uses POST action, it call the [HttpPost]
You can refer this article (from the internet archive as original link is now down): https://web.archive.org/web/20120527133344/http://microsoftmentalist.com:80/2011/09/07/asp-net-mvc-difference-between-httpget-and-httppost-with-example/
See for example how GET and POST action methods are overloaded.
First of all same signature same name method can't be compiled in same controller it will give you the compilation error already have member of same parameter type.
You have to differentiate these two similar name method by different signature.
Regarding HttpPost and HttpGet your get method will be called whenever you have to retrive data or your page load is called for that view.
HttpPost method will be called either you are using button of type submit or your input type is button but using jquery you are giving ajax call on button click and your ajax type is "Post"
$.ajax({
url: "Action"
type: "Post"
},succees: function(){alert('succeed');});

Handing forms in ViewUserControls

I am rendering out a ViewUserControl (.ascx file) in a view:
<% Html.RenderPartial("Comments", Model.Comments); %>
This ViewUserControl shows associated comments on an entry. I would like this control to render out a form as well, so users of my application can contribute.
How would you add a form to a ViewUserControl and handle it's postback?
Just add the form in there the same as you would on any page. In MVC, the form does not postback as such - it simply submits itself and its content (input controls) via HTTP Post to a URL.
Simply create an action in your controller (and hence a URL) which the form will post and do whatever activity is required there...
There is no postaback, like in standard asp.net, there can be only form tag that posts data to some url (controller/action).
Inside your partial user control, write:
<form action="controller/actionname" method="post">
<input type="text" name="inputText" />
<input type="submit" value="Post data to server" />
</form>
In MVC, only input type="submit" triggers form submit. In standard ASP.NET webforms, you can have many Linkbuttons, Buttons, ... but under cover, they all triggers this simple click on input type="submit" through javascript event. One form can post data to only one URL (controller/action), but that can be changed with javascript (as we can see in html source of 'old' asp.net webforms).
then, in controller you can handle post data:
[AcceptVerb(HttpVerb.Post)] // optionally
public ActionResult ActionName(string inputText) ...
Like others have answered already, you simply render a form and handle it's submit with an ActionResult.
For example, if your form (which could be rendered anywhere in your site) was submitting to http://www.yoururl.com/home/save, you would create an ActionResult method named save on the home controller to handle the submit (likely post/get method).

Categories

Resources