On Form POST values are displayed in URL - asp.net

Controller's Action1 calls a view which contains the following HTML code:
#using(Html.BeginForm("Action2","Controller",new {ID = ViewBag.Link},FormMethod.Post,new {#class =""}))
{
#Html.AntiForgeryToken()
<input type="submit" value= "Submit"/>
}
When the user Submits this Form following method is called:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Action2(int ID)
{
//Something
return View("Display");
}
When this "Display" view is displayed the URL contains: //Controller/Action2?ID=1
How to avoid this values from being visible in the URL even after the FormMethod is POST?

It is happening because you're sending the ID as a route value. If you want it to stay out of the URL, instead send it via a hidden input element
#using(Html.BeginForm("Action2"))
{
#Html.AntiForgeryToken()
<input type="hidden" name="ID" value="#ViewBag.Link" />
<input type="submit" value= "Submit"/>
}

Related

How do Delete view and action get the model id?

In a standard MVC app, scaffolding controller with views gives a Delete view with this Razor form:
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
<div class="form-actions no-color">
<input type="submit" value="Delete" class="btn btn-default" /> |
#Html.ActionLink("Back to List", "Index")
</div>
}
Nowhere in the Delete view is any id field, hidden or not.
Then the controller for that view has this action:
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(long id)
{
....
}
Where does this action get its id parameter value from? Is it somehow extracted from the only form value posted, the anti-forgery token __RequestVerificationToken, during some sort of model binding?
The id is passed as parameter when you redirected to the Delete action:
[HttpGet]
public ActionResult Delete(long id)
{
return View();
}
and since it is part of the original url (look at your browser address bar at the moment the Delete view is displayed) it will be preserved by the Html.BeginForm() helper - now look at the generated HTML markup and you will see this:
<form action="/somecontroller/delete/123" method="post">
...
</form>
That's where the id is coming from - the action of the generated form.
Because you have a GET method with a signature
public ActionResult Delete(long id)
and you using the default route (or at least a route definition containing /{id})
url: "{controller}/{action}/{id}"
When you navigate to that method, say using /yourController/Delete/10, the value of id is 10, and that is added to the action attribute of the <form> tag generated by your Html.BeginForm() method. When you submit the form, the value of the id parameter is bound for the route value in the forms action attribute (the DefaultModelBinder reads values from the form collection (any inputs you might have) as well as route values and query strings (among others)

pass values from view to controller

in my html5 page there is a search textbox with a haperlink. when i click on hyperlink value does not goes to controller. i can not use form because on this page i am already using a form.
<input type="text" name="searchval"/>
Go!
and in controller
function user()
dim val as string = Request("searchval")
but searchval always return nothing even i put some text in textbox. Please help
Hyperlinks do not submit forms. You need a form tag and a submit button.
<form action="/users" method="POST">
<input type="text" name="searchval"/>
<input type="submit" value="Go!" />
</form>
You also need to make sure your VB.NET method is routed to appropriately by the form action and is actually a controller action:
Function User() As ActionResult
when you click on hyperlink call ajax function.
function Searchfunction() {
var searchValue = $("#searchval").val();
$.ajax({
url: '#Url.Action("Action", "Controller")',
data: { "searchval": searchValue },
success: function (result) {
$('#dvSearch').html(result);
}
});
}

ASP.NET WEB API Not able to retrieve Post Parameters

I trying to retrieve post parameters in web API but I do get null values everytime.
My html
<form method="POST" action="http://localhost:16192/update" name="myform">
<input name="title" type="text"/>
<input name="isbn" type="text"/>
<input name="author" type="text"/>
<input type="submit" value="Submit"/>
</form>
And My WebAPI
[HttpPost]
[Route("UPDATE/")]
public String updateRecord([FromBody]String title,String isbn="", String author="")
{
return "Updated";
}
The updateRecord method is being called but I always get null values. Any help would be greatly appreciated.
[HttpPost]
[Route("UPDATE/")]
public String updateRecord([FromBody]dynamic values)
{
var title = values.title.Value;
....
return "Updated";
}
or you can create a DTO object (paragraph 2):
http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

ASP.Net MVC 4 Form with 2 submit buttons/actions

I have a form in ASP.Net and razor.
I need to have two ways of submitting said form: one that goes through the Edit action, and another that goes through the Validate action.
How should I go about doing this?
I don't mind using JavaScript for this.
EDIT:
Using the custom attribute I get this error.
The current request for action 'Resultados' on controller type 'InspecoesController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Validar(System.Collections.Generic.ICollection1[Waveform.IEP.Intus.Server.Web.ViewModels.ResultadoViewModel]) on type Waveform.IEP.Intus.Server.Web.Controllers.InspecoesController
System.Web.Mvc.ActionResult Resultados(System.Collections.Generic.ICollection1[Waveform.IEP.Intus.Server.Web.ViewModels.ResultadoViewModel]) on type Waveform.IEP.Intus.Server.Web.Controllers.InspecoesController
That's what we have in our applications:
Attribute
public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
return true;
var request = controllerContext.RequestContext.HttpContext.Request;
return request[methodInfo.Name] != null;
}
}
Actions decorated with it:
[HttpParamAction]
public ActionResult Save(MyModel model)
{
// ...
}
[HttpParamAction]
public ActionResult Publish(MyModel model)
{
// ...
}
HTML/Razor
#using (#Html.BeginForm())
{
<!-- form content here -->
<input type="submit" name="Save" value="Save" />
<input type="submit" name="Publish" value="Publish" />
}
name attribute of submit button should match action/method name
This way you do not have to hard-code urls in javascript
You can do it with jquery, just put two methods to submit for to diffrent urls, for example with this form:
<form id="myForm">
<%-- form data inputs here ---%>
<button id="edit">Edit</button>
<button id="validate">Validate</button>
</form>
you can use this script (make sure it is located in the View, in order to use the Url.Action attribute):
<script type="text/javascript">
$("#edit").click(function() {
var form = $("form#myForm");
form.attr("action", "#Url.Action("Edit","MyController")");
form.submit();
});
$("#validate").click(function() {
var form = $("form#myForm");
form.attr("action", "#Url.Action("Validate","MyController")");
form.submit();
});
</script>
If you are working in asp.net with razor, and you want to control multiple submit button event.then this answer will guide you. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".
#{
if (IsPost)
{
if(Request["btn"].Equals("button_A"))
{
Response.Redirect("PageA.cshtml");
}
if(Request["btn"].Equals("button_B"))
{
Response.Redirect("PageB.cshtml");
}
}
}
<form method="post">
<input type="submit" value="button_A" name="btn"/>;
<input type="submit" value="button_B" name="btn"/>;
</form>
Here is a good eplanation:
ASP.NET MVC – Multiple buttons in the same form
In 2 words:
you may analize value of submitted button in yout action
or
make separate actions with your version of ActionMethodSelectorAttribute (which I personaly prefer and suggest).
With HTML5 you can use button[formaction]:
<form action="Edit">
<button type="submit">Submit</button> <!-- Will post to default action "Edit" -->
<button type="submit" formaction="Validate">Validate</button> <!-- Will override default action and post to "Validate -->
</form>
<input type="submit" value="Create" name="button"/>
<input type="submit" value="Reset" name="button" />
write the following code in Controler.
[HttpPost]
public ActionResult Login(string button)
{
switch (button)
{
case "Create":
return RedirectToAction("Deshboard", "Home");
break;
case "Reset":
return RedirectToAction("Login", "Home");
break;
}
return View();
}
We can have this in 2 ways,
Either have 2 form submissions within the same View and having 2 Action methods at the controller but you will need to have the required fields to be submitted with the form to be placed within
ex is given here with code Multiple forms in view asp.net mvc with multiple submit buttons
Or
Have 2 or multiple submit buttons say btnSubmit1 and btnSubmit2 and check on the Action method which button was clicked using the code
if (Request.Form["btnSubmit1"] != null)
{
//
}
if (Request.Form["btnSubmit2"] != null)
{
//
}

asp.net javascript to db

have been struggling with this. Tried everything I can think of. Im using javascript to pass data to db, works fine with ints on another page but now with strings it wont work :s
#using (Html.BeginForm(null, null, FormMethod.Post, new{#id="manageForm"}))
{
#Html.AntiForgeryToken()
<span class="actions">
#T(User.Id.ToString()) #T(" ") #T(ViewData["Tag"].ToString())
<input type="hidden" name="tag" value="fr" />
<input type="hidden" name="id" value="3" />
#T("Follow")
</span>
}
Javascript
<script type="text/javascript">
function followTag() {
$('#manageForm').attr('action', '#(Url.Action("FollowTag"))').submit();
return false;
}
</script>
Controller
[RequireAuthorization]
[HttpPost]
public ActionResult FollowTag(int id, string tag)
{
_service.FollowTag(id, tag);
return RedirectToAction("TagPage","Detail", new
{
});
}
Data Access
public void FollowTag(int id, string tag)
{
DbCommand comm = GetCommand("SPTagFollow");
//user id
comm.AddParameter<int>(this.Factory, "id", id);
//id to follow
comm.AddParameter<string>(this.Factory, "tag", tag);
comm.SafeExecuteNonQuery();
}
route is setup fine and sql(stored procedure) executes perfect. Hopefully one of you can see something obvious
cheers
I think is a problem of mistyping, check your last <a> tag, you typed following.() in the onclick event, see that your javascript function is called followTag.
If that doesn't fix it, then get rid of that foolowTag function, you can specify the action and the controller in the form itself, like this:
#using (Html.BeginForm("FollowTag", "YourControllerName", FormMethod.Post)) {
...
//Delete this line
//#T("Follow")
//This submit button will do the job
<input type='submit' value='#T("Follow")' />
}
That should do it. If you are using the anchor tag just for styling that's ok, otherwise you should use the other way, I think is clearer and besides it takes advantage of razor's great features.

Categories

Resources