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);
}
});
}
Related
I have a IActionResult on my controller that returns a Partial View via AJAX:
[HttpGet]
[Route("/propertycoverages/loss")]
public IActionResult GetNewLoss()
{
return PartialView("_Loss");
}
If I put an <a> tag in my Razor view with the following:
<a asp-controller="PropertyCoverages" asp-action="GetNewLoss" id="loss-btn" data-ajax="true" data-ajax-update="losses" data-ajax-success="addLoss" data-ajax-method="GET">Add</a>
the following HTML attribute gets generated in the <a> tag: href="/propertycoverages/loss"
it works as expected and the partial view is returned within the page. However, if I try to use a button:
<button asp-controller="PropertyCoverages" asp-action="GetNewLoss" id="loss-btn" type="submit" data-ajax="true" data-ajax-update="losses" data-ajax-success="addLoss" data-ajax-method="GET">Add</button>
the following HTML attribute gets generated in the <button> tag: formaction="/propertycoverages/loss"
and I get redirected to /propertycoverages/loss which is not what I want. Is there a way I can make the button behave like the <a> tag?
Note: These elements are inside a <form>. I also tried switching the <button> from type="submit" to type="button" but the controller action doesn't get called.
You will want to attach a JavaScript method to your button click action.
<button onclick="myFunction()">Click me</button>
In the JS method you can call back to the action get the HTML and lay in on the page in the AJAX call success method.
function onClick() {
var url = [setURL];
$.ajax({
type: "GET",
url: url,
data: { },
success: function (response) {
$('#[setElementToReplace]').html(response);
}
});
}
Hi there are mainly three ways for calling the controller action from the submit button.
Way1: Using simple Form
#using (Html.BeginForm("ActionName", "ControllerName"))
{
<input type="submit" name="add" value="Add" />
}
Note: By default it is a get request, If required you can change formmethod = post
Way 2: Using html Attributes
#using (Html.BeginForm())
{
<input type="submit" name="add" value="Add" formaction="/anycontrollername/anyactionname" formmethod="get"
/>
}
Way 3 : using jquery
#using (Html.BeginForm())
{
<input type="submit" name="add" value="Add" id=”save”
/>
}
$(document).ready(function () {
$("#save").click(function () {
$("form").attr("action", "/anycontroller /anyaction");
});
});
It seems that 2nd way will be suitable for your requirement,
Hope the above answer was useful.
I have a list of forms in a page of my meteor app, the list is generated dynamically and all the forms have the same class.
So i made the event submit on the events area of my template, but when i submit the form, only the first form works, if i submit the second form for example, meteor event understand that the event came from the first, and i don'k know how to pass the form id to meteor events, so i can't get the data from the right form. Someone can help me?
This is my event:
'submit .form-equation': function (e, t) {
e.preventDefault();
var name = t.find('#name').value,
equation = t.find('#equation').value,
order = Number(t.find('#order').value),
isChart = t.find('#isChart').checked;
var equationData = {
name: name,
equation: equation,
order: order,
isChart: isChart
};
var station = Stations.findOne(Session.get('stationNewID'));
var sensorId = t.find('#sensorId').value;
Meteor.call('insertEquation', station, sensorId, equationData, function (error, result) {
if (error)
console.log(error);
});
}
I think there is something else wrong with your application. The behavior you described (having multiple forms of the same class with different IDs) works correctly on a clean example.
Check out the demo I made that demonstrates this: http://meteorpad.com/pad/8CPL2xvS7taeL6jZS/MultipleFormSubmitExample
Basically, the forms look like this:
<template name="example">
<form id="1" class="yolo">
<input type="submit" value="Submit">
</form>
<form id="2" class="yolo">
<input type="submit" value="Submit">
</form>
<form id="3" class="yolo">
<input type="submit" value="Submit">
</form>
</template>
And there is only one event listener:
Template.leaderboard.events({
'submit .yolo': function (e, t) {
e.preventDefault();
alert($(e.target).attr('id'));
}
});
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());
}
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)
{
//
}
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.