How can I pass FORM on a button click in MVC2.0? - asp.net-mvc-2

I am calling a controller method SendMe(formCollection myForm){}.
But I don't know how to pass Form that contains some information. I know how to read it, and also, how to call SendMe() on given controller, but I don't know how to pass it. Though, for the reference I am calling SendMe as:
<div id="menucontainer">
<ul id="menu">
<li><%: Html.ActionLink("Send", "SendMe", "Mail")%></li>
</ul>
</div>
and my SendMe method is:
public ActionResult SendMe(FormCollection Form)
{
string From = Form["From"].ToString();
string Pass = Form["Password"].ToString();
string To = Form["To"].ToString();
string Subject = Form["Subject"].ToString();
string Message = Form["Message"].ToString();
MailMessage nmsg = new MailMessage(From, To, Subject, Message);
nmsg.IsBodyHtml = true;
nmsg.Priority = MailPriority.High;
SmtpClient smtpc = new SmtpClient("smtp.gmail.com", 587);
smtpc.Credentials = new System.Net.NetworkCredential(From, Pass);
smtpc.EnableSsl = true;
smtpc.Send(nmsg);
return View();
}
I haven't put anything in Model, though, MailController and SendMe.aspx are in place.
tell me how to get through this. Thanks in advance.

This simple code should work...if all you need is this to submit information from a form...Please clear if i understood it wrong..I would recommend using a viewmodel or something though to have validation for those fields...and in viewmodel case you should inherit the page from the viewmodel...and retrieve from the viewmodel object instead of formcollection...
<% Html.BeginForm("SendMe", "Send", FormMethod.Post); %> //Here 1st parameter is the actionname while second is the Controller name
//Form Fields....
<input id="SendMe" type="submit" value="Send Info" />
<% Html.EndForm(); %>

In order to obtain the FORM variables in your controller, the form needs to be submitted via a Http POST.
<% using (Html.BeginForm()) {%>
.....
<% Html.EndForm(); %>

Related

how to retrieve select options from my database

I'm trying to retrieve my select option from 3 databases located in a connection that's not my defaut connection.
but I'm getting an error : Undefined variable: marqs (View: C:\wamp64\www\projetSovac\resources\views\home.blade.php)
Here's my controller code
public function index()
{
$marques= DB::connection('sqlsrv2')->table('marque')->get();
$modeles = DB::connection('sqlsrv2')->table('Modele')->select( DB::raw('CodeModele'))->get();
$finitions = DB::connection('sqlsrv2')->table('finition')->select( DB::raw('CodeFinition'))->get();
$marqs = $marques->all(['marque']);
$models = $modeles->all(['CodeModele']);
$Finitions = $finitions->all(['CodeModele']);
return View::make('home')
->with(compact($marqs))
->with(compact($models))
->with(compact($Finitions));
return View('home');
}
and my home.blade.php code
<tr class="filters">
<th><input type="text" class="form-control daterangepicker-field" placeholder="PĂ©riode d'analyse" disabled ></th>
<th><select class="form-control " disabled>
{!! Form::Label('marque', 'marque:') !!}
#foreach($marqs as $marque)
<option value="{{$marque->codeMarque}}">{{$marque->codeMarque}}</option>
#endforeach
</select>
</th>
Can you help identify the problem?
Thanks
compact($marqs) wants to have a string divining the variable you want to pass to the view. Use: compact('marqs') you can also combine your variables like compact('marqs', 'models', ....etc )
Also you are returning something 2 times now in the function this is not possible.
I would rewrite your function to be like this:
$marques= DB::connection('sqlsrv2')->table('marque')->get();
$modeles = DB::connection('sqlsrv2')->table('Modele')->select( DB::raw('CodeModele'))->get();
$finitions = DB::connection('sqlsrv2')->table('finition')->select( DB::raw('CodeFinition'))->get();
$marqs = $marques->all(['marque']);
$models = $modeles->all(['CodeModele']);
$Finitions = $finitions->all(['CodeModele']);
return View::make('home')->with(compact('marqs', 'models', 'Finitions'));
Assuming the first 6 lines get you the actual data all i changed was the return.
You might want to read up on how to use laravel models
https://laravel.com/docs/5.7/eloquent
I am not sure if u have defined any but it could make your code allot simpler.

JAX-RS, #FormParam display result in the same page

I have this program that I am coding, the main thing is mostly to get familiar with Jax-rs and rest API. I am sending from a form in JSP page one input and with POST I pass it to my java Response class(that I use annotation #FormParam), it does what calculation I need and then I get the result in another link, what can i do to take the result just below my button on the same page? For my button function I use javascript, and when I push it I don't want to be redirected and take the result like this.
So i use this form and a javascript function in my jsp to pass the value in my POST method in java throw #FormParam
<form name="Form1" method="post">
<p>
Name : <input type="text" name="malename" id="malename" autofocus
value="enter your name..." />
</p>
<input type="submit" name="action" id="malename" value="I'm feeling lucky"
onclick="OnButton1();"> </form>
function OnButton1() {
document.Form1.action = "webapi/perfectmatcher/mate"
document.Form1.target = "_self"; // Open in a new window
document.Form1.submit(); // Submit the page
//return;
}
Here after i have the value i use two other classes to do the calculations and return the result i need. In a few words i pass a value in my form and when i push the button i am redirected in another link(the path of POST) and i display the result. I want to display the result below my button. I hope the code is helpful and i hope i am clear with my explanation
#POST
#Path("/mate")
#Produces(MediaType.TEXT_PLAIN)
public Response postMaleName(#FormParam("malename") String malename) {
String femalename = NumMatcher.numMatcher(Numberizer.numberizer(malename));
// FemaleName female = new FemaleName(femalename);
female.setName(femalename);
System.out.println(female.getName());
return Response.status(200).entity("Perfect Match for " + malename + " is " + femalename).build();
}
P.S.:The object female that i am trying to create its for testing purposes, i was trying somehow to get the information that i store but i cannot find how!!I used even jsp expressions but i get null value of course ...
<%
FemaleName female = new FemaleName("john");
String string = female.getName();
out.print(string);
%>

Flask request not returning any info from select

I'm trying to set up a simple select dropdown form with Flask. Based on the option chosen, I grab different data from my database, and display it back into a div on my html template. But I can't seem to get the Flask request to register any of the select options. When I print request.form or request.args, I always get empty Dicts. It's probably something simple I'm missing but I can't seem to find the problem. I've gotten this to work with several input and button forms, but I can't get it to work right for selects.
Here is a bit of my html template code, with the form and select. I've tried both GET and POST method in the form.
<div class="options" id="options">
<form class="form-horizontal container-fluid" role="form" method="GET" action="exploresn2.html">
<div class="form-group">
<label for="xaxis" class="col-sm-2 control-label">X-axis:</label>
<div class="col-sm-2">
<select name="xaxis" class="form-control" id="xaxis">
<option selected value="mjd" id="mjd">MJD</option>
<option value="seeing" id="seeing">Seeing</option>
<option value="airmass" id="airmass">Airmass</option>
<option value="hourangle" id="hourangle">Hour Angle</option>
</select>
</div>
</div>
</form>
</div>
In Flask, at first, I tried inside my app
import flask
from flask import request, render_template, send_from_directory, current_app
explore_page = flask.Blueprint("explore_page", __name__)
#explore_page.route('/exploresn2.html', methods=['GET','POST'])
def explore():
xaxis = str(request.args.get("xaxis", "any"))
.... [populate new xaxis variable based on request option selected]
exploreDict['xaxis'] = xaxis
return render_template("exploresn2.html", **exploreDict)
or
mjd = valueFromRequest(key='mjd', request=request, default=None)
if mjd:
mjds = [int(exp.platedbExposure.start_time/(24*3600)) for exp in exposures]
xaxis = mjds
exploreDict['xaxis'] = xaxis
to look for and grab a specific values, or in the first case, any value select. The valueFromRequest is function that grabs data from either GET or POST requests.
but this returns nothing, and then I tried just printing the entire request.args (or request.form) and it returns and empty Dict. Everything I try it still returns empty Dicts. So I'm missing some set up somewhere I think but the form looks right to me?
I'm not sure if this is the actual answer to this problem that I was looking for, but here is what I came up with. I couldn't actually get the Flask to accept a GET request into the original explore method defined, so I implemented a new method in Flask to return a JSON object
#explore_page.route('/getdata', methods=['GET','POST'])
def getData(name=None):
name = str(request.args.get("xaxis", "mjd"))
xaxis = 'populate new xaxis data based on value of name'
data = '(x,y) data array filled with values for plotting'
axisrange = range of x,y data for axes for plot
return jsonify(result=data, range=axisrange)
and then I just made a GET request via javascript to that method whenever the select button changes. So in my exploresn2.html template I have (using Flot for plotting)
$("#xaxis").change(function(){
var newname = $("#xaxis :selected").text();
var axes = plot.getAxes();
options = plot.getOptions();
var plotdata = plot.getData();
// make a GET request and return new data
$.getJSON($SCRIPT_ROOT + '/getdata', {'xaxis':$("#xaxis :selected").val()},
function(newdata){
// set new data
for (var i = 0; i < plotdata.length; ++i) {
plotdata[i].data = newdata.result[plotdata[i].label];
}
// set new axes
axes.xaxis.options.panRange = [newdata.range[0]-50,newdata.range[1]+50];
axes.xaxis.options.axisLabel = newname;
axes.xaxis.options.min = newdata.range[0]-1;
axes.xaxis.options.max = newdata.range[1]+1;
axes.yaxis.options.min = newdata.range[2];
axes.yaxis.options.max = newdata.range[3];
// redraw plot
plot.setData(plotdata);
plot.setupGrid();
plot.draw();
});
});

Linking two jsp pages with Submit Button Liferay

I have a form where I allow user to select some data and submit the form and based on that selection data will be displayed in another jsp.
I have used the following code in first jsp:
<aui:form name="updateDailyAttendance" action = "<%=request.getContextPath()%> /admin/test.jsp" method="post" >
<input type = "date" name = "myDate"/>
<input type = "submit" name = "Submit"/>
</aui:form>
test.jsp is the second JSP. But the code above isn't working. How should I mention the second jsp name in the "action" above so that the above jsp takes me to second jsp. I am using lIferay
instead of passing a url as 'action', you should provide an actionUrl with the jsp page as param.
<portlet:actionURL var="actionName" name="yourMVCPortletFunctionName">
<portlet:param name="jspPage" value="/admin/test.jsp" />
</portlet:actionURL>
<aui:form name="updateDailyAttendance" action = "<%= actionName %>" method="post" >
<input type = "date" name = "myDate"/>
<input type = "submit" name = "Submit"/>
</aui:form>
then in Your Controller:
public void yourMVCPortletFunctionName(ActionRequest actionRequest, ActionResponse actionResponse){
throws PortletException, IOException
//Do your stuff
//Redirect
String redirectUrl = (String)request.getParameter("jspPage");
actionResponse.setRenderParameter("jspPage", redirectUrl);
}
This way you can have actions that do some standard stuff, like handling that "myDate" param, and have them redirect to other pages each time. So calling them from different points (different jsp page or form), will target ta a new redirect each time

ASP.NET MVC2 inline code in view - mixing tags

I've run into a couple different exceptions with this block of code in one of my views:
<% if (Model.Book.ReviewReference == null)
{%>
<%=Html.ActionLink("Rate / review this book", "Create", "Review", null, new { id = "reviewLink" }) %>
<% Html.RenderPartial("CreateReview");
}
else
{%>
<%= Html.ActionLink("Edit this book's rating / review","Edit", "Review", new { reviewID = Model.Book.ReviewID}, new {id = "reviewLink"}) %>
<% Html.RenderPartial("EditReview", Model.Book.Review, new ViewDataDictionary());
} %>
The first error I encountered was described here:
link text
thus the Html.RenderPartial("EditReview", Model.Book.Review, new ViewDataDictionary()) you see towards the end there.
Another problem I encountered is when the if condition is evaluated for a ReviewReference that is in fact null, the else statement is still being reached somehow, and the second partial view is making an unsuccessful attempt to render itself.
Have I used these alternating inline-code tags in an incorrect manner? How does one go back and forth between <% %> and <%= %> properly?
Thank you.
Edit:
OK, I marked an answer too soon. I just tried it with the given code from the answer, and that else block is still being evaluated, and trying to pass null objects to the partial view...darn it.
You are correct in your usage of the tags there.
They aren't 2 alternating styles, but differences in how the view engine deals with different statements. It's not surprising that it can get confusing.
<%= : Think of this as Response.Write(). You supply it with a string.
<% Html.RenderPartial - this is a command given to the view engine to actually render a partial view. You're not giving it a string, but rather telling the view to go get another snippet (partial view), and write it out.
Missing a couple of closing %>
<% if (Model.Book.ReviewReference == null)
{%>
<%=Html.ActionLink("Rate / review this book", "Create", "Review", null, new { id = "reviewLink" }) %>
<% Html.RenderPartial("CreateReview"); %>
<%}
else
{%>
<%= Html.ActionLink("Edit this book's rating / review","Edit", "Review", new { reviewID = Model.Book.ReviewID}, new {id = "reviewLink"}) %>
<% Html.RenderPartial("EditReview", Model.Book.Review, new ViewDataDictionary()); %>
<% } %>
OK, so it turns out my tag usage was fine, but my if condition was off. It needed to be:
if (Model.Book.ReviewReference.EntityKey == null)
I was missing the EntityKey property.