ASP.Net MVC Send a textbox.Text through an ActionLink - asp.net-mvc

I have this controller:
public ActionResult Index(int id)
{
var cust = (from c in dataModel.Customers
where (c.MembershipID == id)
select c).First();
return View(cust);
}
I want to be able to pass through the ID from a text box on the main page. I tried the following but it says 'memberid' does not exist. Any ideas? Thanks.
<asp:TextBox ID="memberid"/>
<%: Html.ActionLink("Customer", "Index", new {id = memberid.Text}) %>
My goal is to Enter a value in a textbox, click a button and then be redirected to a new view showing that users details.

This is only possible using Javascript; you can handle the link's click event and explicitly navigate to the URL.
Using jQuery:
$('#link').click(function() {
location = "/Customer/Index/" + encodeUriComponent($('#memberId').text());
});
If you want to do it without Javascript, you can make a form containing a textbox and an <input type="submit" />.

Since you want the user to click a button, change the link to a button and in the http post method for your main page, Redirect to the Customer/Index view passing in the memberId.

Related

Route to a POST method with model and id

I want to pass in two Ids to my method. The method is called DeleteAttendee and is on my SessionController in the Training area.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteAttendee(int sessId, int attId)
I have created a link to get there that takes you to https://localhost:<port>/Training/Session/DeleteAttendee?sessId=1&attId=3.
<a asp-action="DeleteAttendee" asp-route-attId="#item.Attendee.Id" asp-route-sessId="#Model.Id">Delete</a>
Using the default routing, this page can't be found. What do I need to change or set up to route to this method?
Edit: Apparently the problem is that the link is performing a GET, but I need it to POST. How do I change it?
I think you can accomplish what I want to do with a button control. It will actually work better for me now if I can pass in the model and a specific id. I tried the button below. It looks correct in the markup, but the id keeps getting replaced with the sessionId when the button is clicked.
<button formaction="/Training/Session/DeleteAttendee/#item.Id" formmethod="post">Edit</button>
Can you use a ActionLink instead?
#Html.ActionLink("Delete", "DeleteAttendee", "Session", new { sessId = Model.Id, attId = item.Attendee.Id })
I ended up using a submit button that calls javascript and added the value to the viewmodel to get this done.
On the page:
<input type="hidden" asp-for="SelectedAttendeeId" />
<input type="button" onclick="DeleteAttendee(#item.Id)" value="E" />
In javascript:
function DeleteAttendee(attendeeId) {
var selectedAtt = $('#SelectedAttendeeId');
selectedAtt.val(attendeeId);
var model = $('#frmSession').serialize();
$.post('/Training/Session/DeleteAttendee', model, function (data) {
// success logic here
});
}

Posting form to different MVC post action depending on the clicked submit button

I am using ASP.Net MVC 4. I have multiple buttons on a view.. At present I am calling the same action method; and I am distinguishing the clicked button using a name attribute.
#using (Html.BeginForm("Submit", "SearchDisplay", new { id = Model == null ? Guid.NewGuid().ToString() : Model.SavedSearch }, FormMethod.Post))
{
<div class="leftSideDiv">
<input type="submit" id="btnExport" class="exporttoexcelButton"
name="Command" value="Export to Excel" />
</div>
<div class="pageWrapperForSearchSubmit">
<input type="submit" class="submitButton"
value="Submit" id="btnSubmitChange" />
</div>
}
//ACTION
[HttpPost]
public ActionResult Submit(SearchCostPage searchModel, string Command)
{
SessionHelper.ProjectCase = searchModel.ProjectCaseNumber;
if (string.Equals(Command, Constants.SearchPage.ExportToExcel))
{
}
}
QUESTIONS
Is there a way to direct to different POST action methods on different button clicks (without custom routing)?
If there is no way without custom routing, how can we do it with custom routing?
References:
Jimmy Bogard - Cleaning up POSTs in ASP.NET MVC
You can choose the url where the form must be posted (and thus, the invoked action) in different ways, depending on the browser support:
for newer browsers that support HTML5, you can use formaction attribute of a submit button
for older browsers that don't support this, you need to use some JavaScript that changes the form's action attribute, when the button is clicked, and before submitting
In this way you don't need to do anything special on the server side.
Of course, you can use Url extensions methods in your Razor to specify the form action.
For browsers supporting HMTL5: simply define your submit buttons like this:
<input type='submit' value='...' formaction='#Url.Action(...)' />
For older browsers I recommend using an unobtrusive script like this (include it in your "master layout"):
$(document).on('click', '[type="submit"][data-form-action]', function (event) {
var $this = $(this);
var formAction = $this.attr('data-form-action');
$this.closest('form').attr('action', formAction);
});
NOTE: This script will handle the click for any element in the page that has type=submit and data-form-action attributes. When this happens, it takes the value of data-form-action attribute and set the containing form's action to the value of this attribute. As it's a delegated event, it will work even for HTML loaded using AJAX, without taking extra steps.
Then you simply have to add a data-form-action attribute with the desired action URL to your button, like this:
<input type='submit' data-form-action='#Url.Action(...)' value='...'/>
Note that clicking the button changes the form's action, and, right after that, the browser posts the form to the desired action.
As you can see, this requires no custom routing, you can use the standard Url extension methods, and you have nothing special to do in modern browsers.
BEST ANSWER 1:
ActionNameSelectorAttribute mentioned in
How do you handle multiple submit buttons in ASP.NET MVC Framework?
ASP.Net MVC 4 Form with 2 submit buttons/actions
http://weblogs.asp.net/scottgu/archive/2007/12/09/asp-net-mvc-framework-part-4-handling-form-edit-and-post-scenarios.aspx
ANSWER 2
Reference: dotnet-tricks - Handling multiple submit buttons on the same form - MVC Razor
Second Approach
Adding a new Form for handling Cancel button click. Now, on Cancel button click we will post the second form and will redirect to the home page.
Third Approach: Client Script
<button name="ClientCancel" type="button"
onclick=" document.location.href = $('#cancelUrl').attr('href');">Cancel (Client Side)
</button>
<a id="cancelUrl" href="#Html.AttributeEncode(Url.Action("Index", "Home"))"
style="display:none;"></a>
This sounds to me like what you have is one command with 2 outputs, I would opt for making the change in both client and server for this.
At the client, use JS to build up the URL you want to post to (use JQuery for simplicity) i.e.
<script type="text/javascript">
$(function() {
// this code detects a button click and sets an `option` attribute
// in the form to be the `name` attribute of whichever button was clicked
$('form input[type=submit]').click(function() {
var $form = $('form');
form.removeAttr('option');
form.attr('option', $(this).attr('name'));
});
// this code updates the URL before the form is submitted
$("form").submit(function(e) {
var option = $(this).attr("option");
if (option) {
e.preventDefault();
var currentUrl = $(this).attr("action");
$(this).attr('action', currentUrl + "/" + option).submit();
}
});
});
</script>
...
<input type="submit" ... />
<input type="submit" name="excel" ... />
Now at the server side we can add a new route to handle the excel request
routes.MapRoute(
name: "ExcelExport",
url: "SearchDisplay/Submit/excel",
defaults: new
{
controller = "SearchDisplay",
action = "SubmitExcel",
});
You can setup 2 distinct actions
public ActionResult SubmitExcel(SearchCostPage model)
{
...
}
public ActionResult Submit(SearchCostPage model)
{
...
}
Or you can use the ActionName attribute as an alias
public ActionResult Submit(SearchCostPage model)
{
...
}
[ActionName("SubmitExcel")]
public ActionResult Submit(SearchCostPage model)
{
...
}
you can use ajax calls to call different methods without a postback
$.ajax({
type: "POST",
url: "#(Url.Action("Action", "Controller"))",
data: {id: 'id', id1: 'id1' },
contentType: "application/json; charset=utf-8",
cache: false,
async: true,
success: function (result) {
//do something
}
});

Want to simulate postback in ASP.Net MVC

suppose i have one form and form has two div container. one div container has few textboxes for submiting login details and another div also has few textboxes those related to register. now my home controller has two action method one is login and another is register. i want that when user click on login button then i will submit form through jquery but before submit i will change action url. the same way i want to call register action method when user click on register button. please guide me how could i do this in mvc with jquery. please help me with sample code.
another person answer like in other forum.
#model MvcForums.Models.StudentModel
#{
using(#Html.BeginForm("Create","Student", FormMethod.Post))
{
<label> Name</label>
#Html.TextBoxFor(m=>m.FirstName) <br/>
<label> From country:</label>
#Html.DropDownListFor(m=>m.CountryId, Model.Countries,"--please select-- ") <br/>
<input id="btnSave" value ="Login" type="submit" name="commandName"/>
<input id="btnRegister" value ="Register" type="submit" name="commandName"/>
}
}
[HttpPost]
public ActionResult Create(StudentModel studentModel, string commandName)
{
if(commandName == "Login")
{
}
else if(commandName == "Register")
{
}
return View("Index");
}
after reading his answer some confusion occur in my mind because i am newbie in mvc and those are as follows
first of all ur code is not readable for ill format. i am new in mvc....just learning it. after reading ur code some confusion occur.
1) why extra bracket u gave #{ }
2 u use <label> Name</label> in form building code. in html4 is there any tag ? is it html5 specific tag ?
3) #Html.DropDownListFor(m=>m.CountryId, Model.Countries,"--please select-- ")
when u building dropdown why u did not specify value & text filed.......how mvc can understand what field will be value & what will be text ? u just bind the model with DropDownListFor()
4) just see it
<input id="btnSave" value ="Login" type="submit" name="commandName"/>
<input id="btnRegister" value ="Register" type="submit" name="commandName"/>
both the button name is commandName ? is it correct ?
when user click on any button then how button name will be pass to
public ActionResult Create(StudentModel studentModel, string commandName)
Create() method ? please tell me how implicitly command name will be pass to Create() and how commandName variable at server side can hold the button name.
i have too much confusion after reading ur code. if possible please discuss all my points in details. thanks
i want that when user click on login button then i will submit form
through jquery but before submit i will change action url. the same
way i want to call register action method when user click on register
button.
1. Event on button click:
$(function(){
$("#btnSave").click(function(){
$("#btnSave").closest("form").attr("action", "/home/test");
});
});
2. MarkUp:
<form method="POST" action="/home/test1" >
<input id="btnSave" value="Login" type="submit" name="commandName"/>
</form>
3. Server side:
[HttpPost]
public ActionResult Test(string commandName)
{
return null;
}
1) Razor syntax reference http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx
2) The <label> is not specific html5 tag but it have additional attribute in html5, http://www.w3schools.com/tags/tag_label.asp
3) You can build your IEnumerable of SelectListItem in which specified Text and Value
4) The input name commandName is not important if you don't want to catch client value value ="Login" on server side,

asp.net mvc jquerymobile redirectotroute doesn't change url

I've got an mvc4/jquerymobile application, and I'm having a hard time figuring out why, after returning a RedirectToRoute(rvd) from a controller-action, the redirected-to url is not shown.
I start the process on an Edit page with a form at http://localhost/Report/Params/9. I edit the form, submit it, and the Report controller, Params [HttpPost]action fires up. It validates the form values, munges them around a bit, and then adds the lot of them to a RouteValueDictionary, along with my controller ("Report") and new action ("Render") properties.
This all happens correctly, and I'm taken to the "Render" view, but the URL displayed in the browser remains http://localhost/Report/Params/9
I would like the browsers url to show http://localhost/Report/Params/9?p1=1&p2=2&p3=3 instead, because I want the users to be able to bookmark a parameter-set for later use.
What am I missing? I think the issue is related to jquerymobile's handling of the submit button click. I tried to mitigate that with data-ajax=false, but it doesn't seem to have helped any.
<button type="submit" data-theme="b" name="submit" value="submit-value" data-ajax="false">
Submit
</button>
Thanks
Edit: Here's a close replica of my redirecting function...
public ActionResult Params(FormCollection Params ) {
RouteValueDictionary rvd = new RouteValueDictionary();
// example values //
rvd.Add("controller", "Report");
rvd.Add("action", "Render");
rvd.Add("id", 10);
rvd.Add("p1", 1);
rvd.Add("p2", 2);
rvd.Add("p3", 3);
RedirectToRouteResult rrr = RedirectToRoute(rvd);
return rrr;
}

MVC Html.BeginForm capture key press event

I have an MVC application, and I am using Html.BeginForm to make forms. There are several forms on the page, each representing a tab in a row of tabs. I need to detect the "Enter" key being pressed on one of the tabs. Anyone know how to do this?
Code example -
<div>
#using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new { id = "MyForm1" }))
{
<div id="divId">
</div>
}
</div>
Thanks!
#using (Html.BeginForm("Create", "ApplicationSchedule", FormMethod.Post,
new { onkeydown = "return event.keyCode!=13" }))
You are able to add event listeners to the form using the htmlAttributes object parameter as I have done using the new { onkeydown = "return event.keyCode!=13" } section in the code. In my case I am ignoring the enter key when it is pressed in the form using the onkeydown listener. This is easily replaceable using your own code such as onkeydown = "yourJavascriptFunction()" to achive whatever it is you need to achieve when the enter key is pressed in the form. For more info on the parameters accepted for the Html.BeginForm(), see MSDN

Resources