How to redirect #Url.Action - asp.net

I have link with parameter:
[http://localhost:8545/Admin/Agent/ManageUser?agentId=3230][1]
After change language new link:
[http://localhost:8545/Admin/Agent/ManageUser][2]
have error beacause haven't ?agentId=3230
i use :<input type="hidden" name="ReturnUrl" value="#Url.Action(null)" />
i don't know edit #Url.Action(null), please help me. thanks!

try this input
<input type="hidden" name="ReturnUrl" value="#Url.Action(ViewContext.RouteData.Values["controller"].ToString(), ViewContext.RouteData.Values["action"].ToString(), new { agentId = Request.QueryString["agentId"] })" />
Firs parameter if Url.Action is controller name, second parameter is action name and last one the routeValues can you add query strings in URL.

If you just need to return the user to the same URL he was before changing the language, just keep the full URL in your hidden input as follows:
<input type="hidden" name="ReturnUrl" value="#Request.Url.AbsoluteUri" />
Also (assuming your ChangeLanguage method is accessibly using the same host-name), you could simply do:
public ActionResult ChangeLanguage(string lang)
{
// something like...
// Session["Lang"] = lang;
return Redirect(Request.UrlReferrer.ToString());
}

Related

how to get data from a form("multipart/form-data") with springMvc?

how to get data from a form("multipart/form-data") with springMvc?
i want to upload a file(a photo),so the type of form is 'multipart/form-data'
but i found that springMVC cannot map data(in the form) into the property of User,I know i should use multipartFile to accept the picture,but how can other data in the form be mapped into object User automatically ?
<form enctype="multipart/form-data" type="post" action="....">
<input type"file" name="photo"/>
<input type"text" name="username"/>
.....
</form>
#RequestMapping("...")
public String editUser(User user,MultipartFile multipartFile){
.....
}
I get a 400 bad request error,so does anyone know how to achieve it? thanks a lot if someone help me out
You can do like this:-
<form enctype="multipart/form-data" type="post" action="....">
<input type"file" name="photo"/>
<input type"text" name="username"/>
.....
</form>
add model attribute on this page and use it in
your controller like this:-
#RequestMapping("...")
public String editUser(#RequestParam("photo") MultipartFile photo,
#ModelAttribute("your model attribute") User user){
.....
}

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 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.

Javascript cannot find hidden Field in ASP.NET?

I am trying save the disabled property value of a hidden field to track the disabled state of a button between postbacks, with the following javascript
function TrackState(buttonID)
{
var trackingField = document.getElementById("_tracking" + buttonID);
return false; // prevent default action
}
HTML
<input type="hidden" name="_trackingButton1" value="true" />
but trackingField seems to be null each time, what is going wrong here
You need to assign the id property of your element (not just name) and it should work like this:
<input type="hidden" id="_trackingButton1" name="_trackingButton1" value="true" />
I hope this helps.
In your function
function TrackState(buttonID)
{
}
what is the buttonID value exactly. I hope it is "Button1".
And as the function says getElementById the input has the property id with the same value.
The getElementById() method specifically looks for id values:
<input type="hidden" id="_trackingButton1" name="_trackingButton1" value="true" />

Resources