webform with one text box and two buttons - asp.net-mvc

How can I have two buttons posting to different actions for the same text box?
for eg: I have two buttons "Get Student(xls)" and "Get Student(pdf)" and I want to trigger different ActioResult methods. I am only able to trigger one method for launching excel, which is: "/Student/StudentExcel/" The second method for launching pdf is: "/Student/StudentPdf/".
Here is my screenshot for the form:
Here is my code for the view page:
<%# Page language="c#" AutoEventWireup="true" %>
<%# Import NameSpace="System.IO" %>
<%# Import NameSpace="System" %>
<%# Import NameSpace="System.Data" %>
<%# Import NameSpace="System.Web" %>
<%# Import NameSpace="System.Text" %>
<%# Import Namespace="STUDENT.Controllers" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Get Student File</title>
</head>
<body>
<div>
<form method="post" action="/Student/StudentExcel/">
<label for="id">Student Number: </label>
<input type="text" name="id" value="" />
<br /><br />
<input type="submit" value="GetStudent(xls)"/> &nbsp
<input type="submit" value="Get Student(pdf)" />
</form>
</div>

How can I have two buttons posting to different actions for the same text box?
You can't do this without javascript and plain HTML.
Let me suggest you an alternative: you could use two submit buttons with different names that submit to the same controller action and inside this controller action you could retrieve the name of the submit button that was clicked and act accordingly.
<form method="post" action="/Student/Dispatch/">
<label for="id">Student Number: </label>
<input type="text" name="id" value="" />
<br /><br />
<input type="submit" value="Get Student(xls)" name="xls" />
&nbsp
<input type="submit" value="Get Student(pdf)" name="pdf" />
</form>
and inside the Dispatch action:
[HttpPost]
public ActionResult Dispatch(string pdf, string id)
{
if (!string.IsNullOrEmpty(pdf))
{
// The GetPdf submit button was clicked
return StudentPdf(id);
}
// The GetXls submit button was clicked
return StudentExcel(id);
}

Related

Get method : form input not in url

I am doing my first ASP.NET mvc project, on the home page, Index.cshtml, I have a small form:
<form action="ChoixFormulaire" method="get">
<fieldset>
<label>NAS</label>
<input id="nas" type="text" placeholder="###"/>
<br />
<label>Date of birth</label>
<input id="date" type="text" placeholder="AAAA-MM-JJ"/>
<br />
<label>Employee number</label>
<input id="numEmployee" type="text" placeholder="######"/>
<br />
</fieldset>
<input type="submit" value="Soumettre" onclick="return VerifierFormulaire()" />
</form>
When the button is clicked, there is some verification made in the 'VerifierFormulaire()' method, which is defined in the same Index.cshtml file. Then the ChoixFormulaire.cshtml is displayed (called from the ChoixFormulaire() method in my HomeController, which returns View()).
I was expecting the form inputs to be in the URL as parameters. For example, If I enter '123' for NAS, '1989-01-01' for date of birth and '123456' for employee number, I am redirected to http://localhost:15778/Home/ChoixFormulaire? but I would expect to be redirected to http://localhost:15778/Home/ChoixFormulaire?nas=123&dateBirth=1989-01-01&numEmployee=123456
Try adding the name attribute:
<input id="nas" name="nas" />

unable to display the validation messages from #Html.ValidationSummary() in MVC view

I have a fairly simple form created in a partial view and loading the form on a jquery dialog. The view is tightly bound to a model. When the user clicks on the submit button with out entering any inputs, I need to show the validation messages.
<div>
<form method="post" enctype="multipart/form-data" id="ssimForm" action="Home/ProcessUploadedFile"
onsubmit="return false;">
<div>
<h3>
Select the file to be uploaded :</h3>
<span>
<input type="file" name="UploadFileName" id="UploadFileName" /></span>
</div>
<div>
<h3>
Select the date range :</h3>
<span class="uslabel">From Date(MM/dd/yyyy): </span>
<input class="usdate" id="usfromdate" name="StartDate" type="date" />
<span class="uslabel">To Date(MM/dd/yyyy): </span>
<input class="usdate" id="ustodate" name="EndDate" type="date" />
</div>
<div>
<br />
<input type="submit" id="submitButton" name="submitButton" value="Process File" />
</div>
#Html.ValidationSummary()
<div class="message-success">
<span>#ViewBag.Confirmation</span>
</div>
<div class="message-error">
<span>#ViewBag.Error</span>
</div>
</form>
</div>
Now comes the actual problem. when I submit the form I am able to see the validationSummary object populated with the messages, but they are not getting rendered on the screen.
I am able to see the messages if I replace the content of the dialog with the response from the jquery ajax call, that fetches the entire view from the server side. I do not want to take this approach as I beleive this is not the correct way to return validation summary in MVC.
Am I missing something? Any help is appreciated.
I don't know why you don't have the #using (Html.BeginForm()) { } block.
Here is my blog post for a quick and easy way to set up Validation Summary + Unobtrusive Validation for MVC3+.
http://geekswithblogs.net/stun/archive/2011/01/28/aspnet-mvc-3-client-side-validation-summary-with-jquery-validation-unobtrusive-javascript.aspx

Form reloads the page but does not submit

I'm working on Asp.net MVC Application. When I use a form and try to submit , it just reloads the page. I have included the method and Action info , but the form and data are not sent to address specified in action attribute of form. Any help please
<form action="/Search/SearchforQuery/" method="post" runat="server">
<p>Search : <input style="font-size:medium; width: 600px; height: 29px;"
name="searchField" id="searchField" /></p>
</div> <input type="submit" value="Submit Form" />
</form>
Why are you using runat="server" if you are using MVC?
Delete it.
Try to use:
#{ using (Html.BeginForm(...))
{
<p>
Content here
</p>
}

MVC - Cannot seem to post to controller action using AJAX helper

I'm having issues posting a model to a controller action using the AJAX helper. The controller action doesn't get hit at all.
Code:
View:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ServiceNumberModel>" %>
<div id="ServiceNumberPanel">
<h1>
Based on your location we offer different plans</h1>
<% using (Ajax.BeginForm("AvailablePlans", "ServiceCheck", new AjaxOptions { UpdateTargetId = "AdslPlansPanel", HttpMethod = "Post" } ))
{ %>
<%=Html.ValidationSummary(true)%>
Your Phone Number:
<%=Html.TextBoxFor(m => m.HomePhoneNumber)%><br />
<%=Html.CheckBoxFor(m => m.BundleWithHomePhone)%>Bundle with Home Phone? <br/>
<input id="CheckServiceAvailabilityButton" type="submit" value="Check"/>
<% } %>
</div>
Model:
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace ServiceCheck
{
public class ServiceNumberModel
{
[Required(ErrorMessage = "Please enter your phone number.")]
[RegularExpression(#"^[0]\d{9}$", ErrorMessage = "Please enter your phone number, including the area code")]
[DisplayName("Phone Number:")]
public string HomePhoneNumber { get; set; }
public bool BundleWithHomePhone { get; set; }
}
}
Controller:
[HttpPost]
public ActionResult AvailablePlans(ServiceNumberModel serviceNumberModel)
{
if (serviceNumberModel.BundleWithHomePhone)
return ReturnAvailableBundledPlans(serviceNumberModel);
return View("Index");
}
Generated HTML:
<div id="ServiceNumberPanel">
<h1>
Based on your location we offer different plans</h1>
<form action="/ServiceCheck/AvailablePlans" data-ajax="true" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-update="#AdslPlansPanel" id="form0" method="post">
Your Phone Number:
<input data-val="true" data-val-regex="Please enter your phone number, including the area code" data-val-regex-pattern="^[0]\d{9}$" data-val-required="Please enter your phone number." id="HomePhoneNumber" name="HomePhoneNumber" type="text" value="" /><br />
<input data-val="true" data-val-required="The BundleWithHomePhone field is required." id="BundleWithHomePhone" name="BundleWithHomePhone" type="checkbox" value="true" /><input name="BundleWithHomePhone" type="hidden" value="false" />Bundle with Home Phone? <br/>
<input id="CheckServiceAvailabilityButton" type="submit" value="Check"/>
</form>
</div>
Behaviour:
When I click on submit, I get 'Resource cannot be found error':
The resource cannot be found. Description: HTTP 404. The resource you
are looking for (or one of its dependencies) could have been removed,
had its name changed, or is temporarily unavailable. Please review
the following URL and make sure that it is spelled correctly.
Requested URL: /ServiceCheck
Interestingly when I look at the source using firebug, I cannot see the form tags:
<div class="ExistingContent">
<h1>ServiceCheck</h1>
<div id="ServiceNumberPanel">
<div id="ServiceNumberPanel">
<h1> Based on your location we offer different plans</h1>
Your Phone Number:
<input id="HomePhoneNumber" type="text" value="" name="HomePhoneNumber" data-val-required="Please enter your phone number." data-val-regex-pattern="^[0]\d{9}$" data-val-regex="Please enter your phone number, including the area code" data-val="true">
<br>
<input id="BundleWithHomePhone" type="checkbox" value="true" name="BundleWithHomePhone" data-val-required="The BundleWithHomePhone field is required." data-val="true">
<input type="hidden" value="false" name="BundleWithHomePhone">
Bundle with Home Phone?
<br>
<input id="CheckServiceAvailabilityButton" type="submit" value="Check">
</div>
<div id="Div1">
</div>
</div>
Also, if I change the view to use the HTML helper it hits the controller without issue:
<div id="Div1">
<h1>
Based on your location we offer different plans</h1>
<% using (Html.BeginForm("AvailablePlans", "ServiceCheck"))
{ %>
<%=Html.ValidationSummary(true)%>
Your Phone Number:
<%=Html.TextBoxFor(m => m.HomePhoneNumber)%><br />
<%=Html.CheckBoxFor(m => m.BundleWithHomePhone)%>Bundle with Home Phone? <br/>
<input id="Submit1" type="submit" value="Check"/>
<% } %>
</div>
Please help!!!
I managed to find the issue.
In the master page I was using, which is shared across a number of applications, someone had added a rouge form:
<body>
<form id="form1" runat="server">
<uc1:header id="Header1" runat="server" />
<div class="ExistingContent">
<asp:contentplaceholder id="MainContent" runat="server" />
</div>
<uc2:footer id="Footer1" runat="server" />
</form>
</body>
This meant that I was trying to submit a form from within a form and the framework was defaulting to the parent.
Once removed, everything began to work as expected.

how to read selected radio button value in Grails?

I'm having a GSP page like below. The requirement is like a list of reports will be shown - the user has the option to select one report and can export the report to excel.
How to read the selected radio button and pass the selected value as "params" ?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="layout" content="main" />
</head>
<body>
<div class="nav">
<span class="menuButton"><g:link class="create"
action="excelExport" params="['id':{ radId.value}]">Export To Excel</g:link>
</span>
</div>
<div class="body">
<div class="message">Select the report and click 'Excel Export'</div>
</div>
<g:form method="post">
<g:render template="displayUploadedReportsTemplate"
model="['uploadedReports':uploadedReports]" />
</g:form>
</body>
</html>
where displayUploadedReportsTemplate is:
<tbody>
<g:each in="${uploadedReports}" var="bbkRat">
<tr>
<td valign="top"><g:radio name="radId"
value="${fieldValue(bean:bbkRat,field:'id')}" /></td>
<td valign="top"><label> ${fieldValue(bean:bbkRat,field:'cmpName')}
</label></td>
<td valign="top"><label> ${fieldValue(bean:bbkRat,field:'reportCreationDate')}
</label></td>
<%--<td valign="top">
<label> ${fieldValue(bean:bbkRat,field:'cmpName')}
</label>
</td>
--%>
<tr>
</g:each>
</tbody>
How should the params value be below??
<g:link class="create"
action="excelExport" params="['id':{ radId.value}]">
i would recommand to use a radio button group. instead of using g:readio tag you can replace it with plain html input tag within you each tag, e.g.
<input type="radio" name="myGroup" value="1" checked="checked" />
<input type="radio" name="myGroup" value="2" />
<input type="radio" name="myGroup" value="3" />
you have already defined a form around your displayUploadedReportsTemplate. so you need to add a submit button to this form and a action where the params should be tramsitted, e.g.
<g:form method="post" action="test">
within test action you can print your params.myGroup and you will recieve to selected report.
<g:link is processed on server-side, so you can't use it on client side, you have to use javascript instead.
It would be like:
<a href="#" class="excelExport" onclick="doExport(); return false">
<script type="text/javascript">
function doExport() {
var id= $('input:radio[name=radId]:checked').val();
window.location = '${g.createLink(action:'excelReport')}?id=' + id;
}
</script>
ps I assume that you are using jQuery

Resources