how to get data from my forms - asp.net-mvc

i'm trying to get the data of my forms on my post metod using
public ActionResult EntradaPedidos(FormCollection formulario) {
Pedidos miPedido = new Pedidos();
UpdateModel(miPedido);
miPedido.division = Request.Form["division"];
what i'm doing wrong? i link my model in the view, and try using different forms.
http://imageshack.us/photo/my-images/13/sinttuloamq.png/
http://imageshack.us/photo/my-images/585/sinttuloecp.png/
this is my view
<% using (Html.BeginForm("EntradaPedidos","home",FormMethod.Post )){ %>
<% =Html.ValidationSummary("") %>
<p>
<label>Division: </label>
<%= Html.DropDownList("division", (SelectList)ViewData["divisiones"]) %>
<!--<%= Html.TextBox("clave1", Model.clave1) %>-->
</p>
<p>
<label>Número del pedido: </label>
<label id="numPedido"><% =Html.Encode(Model.numPedido) %></label>
<!--<% =Html.TextBox ("numeroPedido") %>-->
</p>
<p>
<label> Fecha: </label>
<% =Html.TextBox ("FechaInicio") %>
</p>
<p>
<label>Tipo de pedido: </label>
<% =Html.RadioButton ("tipoPedido", "1") %><label class="inline" for="TipoPedido">1</label>
</p>
<p>
<label>Transacción de pedido: </label>
<% =Html.RadioButton("transPedido", "D2") %> <label class="inline" for="TransPedido">D2</label>
</p>
<p>
<label>Codigo del cliente :</label>
<% =Html.TextBox ("codigoCliente") %>
<label id="lbNombreCliente">Nombre del Cliente: </label>
</p>
<p>
<label>Bodega: </label>
<% =Html.RadioButton("bodega", "CD") %><label class="inline" for="Bodega">CD</label>
</p>
<p>
<label>Lista de Precios: </label>
<label id="lbListaPrecios"> </label>
<%= Html.DropDownList("ddListaPrecios") %>
<!-- <%= Html.CheckBox("cbCambioLista") %> <label class="inline" for="cbCambioLista">Desea cambiar lista de precios?</label> -->
</p>
<p>
<label id="lbCondPago">Condiciones de Pago: </label>
</p>
<p>
<label>Vendedor: </label>
<%= Html.DropDownList("ddListaVendedores") %>
</p>
<p>
<label>Concepto Contable: </label>
<label id="lbConContable"> 03 </label>
</p>
<p>
<label>Ciudad: </label>
<% =Html.DropDownList ("ddCiudad") %>
<label>Punto de entrega: </label>
<%= Html.DropDownList("ddPuntosEntrega") %>
</p>
<p>
<input type="submit" value="Siguiente"/>
</p>
<p>
<%= Html.ActionLink("Menu opciones" , "Menu") %>
</p>
<%} %>

Pass your model to the View:
var pedidos = new Pedidos { division = "teste" };
return View(pedidos);
then tell the view what is its model:
<%# Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcProject.Models.Pedidos>" %>
and expect it on your action method
public ActionResult EntradaPedidos(Pedidos miPedido) {
var division = miPedido.division

Related

Rails form get input value before submitting

I have a rails form which is separated in 3 steps, the first step is for the date selected, second step the time select and last step user info's.
Here is the form code :
<%= form_for [#school, Meeting.new], html: { id: 'meeting_form' } do |f| %>
<!-- one step -->
<div class="step">
<section class="container">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<div class="input-group date" id="datetimepicker1">
<%= f.text_field :date, class: 'form-control date_value', :required => true %>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</section>
<button type="button" class="btn btn-primary next-step" style="width: 100%;"> Suite </button>
</div>
<!-- end one step -->
<!-- second step -->
<div class="step">
<section class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker2'>
<%= f.hidden_field :mhour, required: true, class: "Vroomvroom-timepicker--value-js", :value => "" %>
<div class="scheduler--picker">
<% for time in 8..20 %>
<% if time < 10 %>
<div class="scheduler--picker-line-item <% if #school.meeting_already_booked?("0#{time}:00") %>scheduler--picker-line-item--disabled <% end %>" data-value="0<%= time %>:00">
<p>0<%= time %>:00</p>
</div>
<% else %>
<div class="scheduler--picker-line-item <% if #school.meeting_already_booked?("#{time}:00") %>scheduler--picker-line-item--disabled <% end %>" data-value="<%= time %>:00">
<p><%= time %>:00</p>
</div>
<% end %>
<% end %>
</div>
</div>
</div>
</div>
</div>
</section>
<button type="button" class="btn btn-primary previous-step" style="width: 49%;"> Retour </button>
<button type="button" class="btn btn-primary next-step" style="width: 49%;"> Suite </button>
</div>
<!-- end second step -->
<!-- third step -->
<div class="step">
<section class="container">
<div class="row">
<div class='col-sm-6' style="padding-left: 0;">
<div class="form-group">
<label for="name"> Nom </label>
<%= f.text_field :name, html: 'form-control', :required => true, placeholder: 'Votre nom de famille' %>
</div>
<div class="form-group">
<label for="firstname"> Prénom </label>
<%= f.text_field :firstname, html: 'form-control', :required => true, placeholder: 'Votre prénom' %>
</div>
<div class="form-group">
<label for="email"> Adresse email </label>
<%= f.email_field :email, html: 'form-control', :required => true, placeholder: 'Votre adresse mail, ex: jean.marc#gmail.com' %>
</div>
<div class="form-group">
<label for="phone"> Numéro de téléphone</label>
<%= f.text_field :phone, html: 'form-control', :required => true, placeholder: 'Votre numéro de téléphone, ex: 0606060606', :maxlength => 14 %>
</div>
<div class="form-group">
<label> Pour quel type de permis : </label>
<%= f.select :category do %>
<option value="code">Code uniquement</option>
<option value="moto">Permis A (moto)</option>
<option value="voiture">Permis B (voiture)</option>
<option value="am">Permis AM </option>
<option value="formation">Formations 125 cm3 </option>
<option value="autre">Une autre formation</option>
<% end %>
</div>
</div>
</div>
</section>
<button type="button" class="btn btn-primary previous-step" style="width: 49%;"> Retour </button>
<%= button_tag 'Envoyer', :type => :submit, :class => 'btn btn-primary end' %>
</div>
<!-- end thirs step -->
<% end %>
for the date picker, I use bootstrap-datetimepicker for rails, but I create my own time picker, generated with div and data-attributes. I need to get the value of date before submitting the form to know which hours are already taken in DB to disable them.
I have created a method in the model School:
# meetings
def meeting_already_booked?(date, hour)
if Meeting.where(:date => date).where(:time => hour)
return true
else
return false
end
end
And I use the method here :
<div class="scheduler--picker-line-item <% if #school.meeting_already_booked?("0#{time}:00") %>Vroomvroom-scheduler--picker-line-item--disabled <% end %>" data-value="0<%= time %>:00">
I have the time, but I need the date that user selects the step just before to search in my DB if this hour is already taken.
Your best bet is to save the date locally on click of next button, something like
$("#next_step_button").on("click", function(event) {
localStorage.setItem("date", $(#datetimepicker1).val());
});
To get the value back,
localStorage.getItem("date");

Iterate 4 Arrays with Rails

I'm new to Rails and I'm trying to build a nice application and I'm struggling with arrays, I have 4 arrays that I want to iterate and they are not the same size
I want to generate sections in HTML using the first array what I did it
#sections = ['Section One','Section Two','Section Three','Section Four']
#itemsOne = ['item 1','item 2','item 3','item 4','item 5','item 6']
#itemsTwo = ['item 1','item 2','item 3','item 4','item 5','item 6']
I was using
<%= #sections.zip(#itemsOne, #itemsTwo).each do |t1, t2, t3| %>
<%= t1 %>
<table>
<tbody>
<tr>
<td>
<%= t2 %> | <%= t3 %>
</td>
<td>
<%= t2 %> | <%= t3 %>
</td>
<td>
<%= t2 %> | <%= t3 %>
</td>
</tr>
</tbody>
</table>
<% end %>
I have a table that have a Section Title and cells that have two values
but what I get is the value of |t2| in each cell of |t1| section
using #Phil answer down below, but he deleted it.
<%= #sections.zip(#itemsOne, #itemsTwo).each do |t| %>
<%= t[0] %>
<table>
<tbody>
<tr>
<td>
<%= t[1] %> | <%= t[2] %>
</td>
<td>
<%= t[1] %> | <%= t[2] %>
</td>
<td>
<%= t[1] %> | <%= t[2] %>
</td>
</tr>
</tbody>
</table>
<% end %>
p.s. the itemsOne and itemsTwo arrays have more than 20 values.
What I created is separated my big arrays into smaller ones and then Iterated thru each this way without a Table because table was making design issues so i went into div's using bootstrap 3 column, there might be a better way but this is what i got as a beginner.
<div class="row">
<div class="col-md-12">
<h4><%= #Sections[0] %></h4>
<!-- This will Display Section 0 in the Array -->
</div>
<div class="row">
<div class="col-md-12">
<% #count = 0 %>
<!-- Counter is Zero -->
<% #ItemsOne.collect do |t1| %>
<!-- This will loop array to increment the #count and repeat the HTML -->
<% #count += 1 %>
<!-- With each loop increment by 1-->
<div class="col-md-3">
<div class="col-md-12">
<label>
<input type="checkbox" name="optionsCheckboxes">
<%= #ItemsOne[#count - 1] %>
<!-- Counter should start from 0 adding -1 will make it start
from 0 instead of 1 and then will print the value of the Index Number -->
</label>
</div>
</div>
<% end %>
</div>
</div>
</div>
Here is another way to do this
<div class="row">
<% #Sections.each_with_index do |x1, n| %>
<div class="row">
<div class="col-md-12">
<h4><%= #Sections[n] %></h4>
</div>
<div class="row">
<div class="col-md-12">
<% if n == 0 %>
<% #itemsOne.each_with_index do |t1, n| %>
<div class="col-md-3">
<div class="col-md-12">
<label>
<input type="checkbox" name="optionsCheckboxes">
<%= #itemsOne[n] %>
</label>
</div>
</div>
<% end %>
<% elsif n == 1 %>
<% #itemsTwo.each_with_index do |t1, n| %>
<div class="col-md-3">
<div class="col-md-12">
<label>
<input type="checkbox" name="optionsCheckboxes">
<%= #itemsTwo[n] %>
</label>
</div>
</div>
<% end %>
<% elsif n == 2 %>
<% #itemsThree.each_with_index do |t1, n| %>
<div class="col-md-3">
<div class="col-md-12">
<label>
<input type="checkbox" name="optionsCheckboxes">
<%= #itemsThree[n] %>
</label>
</div>
</div>
<% end %>
<% elsif n == 3 %>
<% #itemsFour.each_with_index do |t1, n| %>
<div class="col-md-3">
<div class="col-md-12">
<label>
<input type="checkbox" name="optionsCheckboxes">
<%= #itemsFour[n] %>
</label>
</div>
</div>
<% end %>
<% end %>
</div>
</div>
</div>
<% end %>
</div>

Why "error_message" don't show error ActiveRecord validate?

Im worked on a project that create events.But I click on a "create event" button with empty fields partial "_error_messages" don't render list with a errors.The page the page is loaded again.Validates seems to be working, in rails console I tried to create and bash show me an error "can't be blank".
This is my _event_form.html.erb
<%= form_for event, html: { class: "event-form" } do |f| %>
<%= render 'shared/error_messages', event: event %>
<% unless current_user %>
<div class='row'>
<div class='col-md-4'>
<div class="form-group col-sm-12">
<%= label :email, "Введите Ваш email:" %>
<%= text_field_tag :email, "",class: "form-control" %>
<small>Он нужен для того, что бы Вы могли позже отредактировать добавленное Вами событие.</small>
</div>
</div>
</div>
<% end %>
<div class="row">
<div class="col-md-8">
<div class="form-group col-sm-12">
<%= f.label "Название" %>
<%= f.text_field :name, class: "form-control" %>
</div>
<div class="form-group col-sm-4">
<%= f.label "Изображение" %>
<%= image_tag event.image, class: "img-responsive" if event.image.present? %>
<%= f.file_field :image %>
</div>
<div class="form-group col-sm-4">
<%= f.label "Город" %><br />
<%= select_tag :city_id, options_from_collection_for_select(City.all, :id, :name), name: "event[city_id]", placeholder: "Город" %>
<%#= f.file_field :image %>
</div>
<div class="form-group col-sm-12">
<%= f.label "Описание" %>
<%= f.text_area :description, class: "form-control", rows: 10 %>
</div>
<div class="form-group col-sm-12">
<%= f.label "Адрес" %>
<%= f.text_field :address, class: "form-control", id: :address %>
<div id='map'></div>
</div>
</div>
<div class="col-md-4">
<div class="form-group col-sm-6">
<%= f.label "Цена от" %>
<input name="event[price][min_price]" value="<%= event.price.try(:min_price) %>" class="form-control" type="number" min="0" />
<%= f.label "Цена до" %>
<input name="event[price][max_price]" value="<%= event.price.try(:max_price) %>" class="form-control" type="number" />
<%= f.label "Тип цены" %>
<br />
<%= select_tag :price_types, options_from_collection_for_select(PriceType.all, :id, :name), name: "event[price][price_type_id]", placeholder: "Выберите тип цены" %>
</div>
<div class="form-group col-sm-6">
<%= f.label "Время проведения" %>
<%= f.text_field :time, class: "form-control", type: :time %>
</div>
<div class="form-group col-sm-6">
<%= f.label "Тип отдыха" %>
<br />
<%= select_tag :types, options_from_collection_for_select(Type.all, :id, :name, selected: event.types.pluck(:id)), name: "event[types_ids][]", placeholder: "Тип отдыха" %>
</div>
<div class="form-group col-sm-12">
<%= f.label "Дата проведения" %>
<div id="mdp"></div>
<input type='hidden' name="event[days]" class="form-control" id="mdp_alt" />
</div>
</div>
</div>
<div class="form-group text-right">
<%= f.submit class: "btn btn-primary" %>
</div>
<% end %>
<script>
$(document).ready(function(){
var dates = <%= event.days.pluck(:date).map{ |d| d.to_s.to_datetime.to_i * 1000 } %>;
if(dates.length){
var settings = {
altField: '#mdp_alt',
dateFormat: "yy-mm-dd",
addDates: dates
}
}else{
var settings = {
altField: '#mdp_alt',
dateFormat: "yy-mm-dd"
}
}
$('#mdp').multiDatesPicker(settings);
})
</script>
this is my _error_messages.erb
<% if event.errors.any? %>
<div id="errorExplanation">
<h2> В форме обнаружено <%= pluralize(event.errors.count, "ошибка", "ошибки") %>:</h2>
<ul>
<% event.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
what's wrong?

Problems with OpenForum Index.ascx?

This is the ascx page:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<OpenForum.Core.ViewModels.IndexViewModel>" %>
<%# Import Namespace="OpenForum.Core.Views.ForumViewHelper" %>
<div class="openforum_container">
<%= (Model.IncludeDefaultStyles) ? ForumViewHelper.GetDefaultStyles() : ""%>
<%= (Model.IncludeValidationSummary) ? Html.ValidationSummary() : ""%>
<div class="openforum_actions">
<%= Html.ActionLink("Write A New Post", "Post") %>
</div>
<div class="openforum_search">
<% Html.BeginForm(); %>
Search: <%= Html.TextBox("searchQuery") %> <input type="submit" value="go" />
<% Html.EndForm(); %>
</div>
<div class="openforum_message"><%= Model.Message %></div>
<table class="openforum_maincontent">
<% foreach(var item in Model.Posts ?? new Post[0]) { %>
<tr>
<td class="openforum_title"><%= Html.ActionLink(item.Title, "view", new { id = item.Id, title = ForumViewHelper.ToUrlFriendlyTitle(item.Title) })%></td>
<td class="openforum_user">
<div>created by <%= Html.Encode(item.CreatedBy.Username) %></div>
<div><%= item.CreatedDate.ToString("MM/dd/yyyy hh:mm tt") %></div>
</td>
<td class="openforum_modified">
<div>last post by <%= Html.Encode(item.LastPostBy.Username) %></div>
<div><%= item.LastPostDate.ToString("MM/dd/yyyy hh:mm tt") %></div>
</td>
<td class="openforum_replies">Replies: <%= item.Replies.Length %></td>
<td class="openforum_views">Views: <%= item.ViewCount %></td>
</tr>
<% } %>
</table>
<div class="openforum_index_paging">
<% if ((Model.Posts ?? new Post[0]).Count() > 0) { %>
<span>Page <%= Model.CurrentPage + 1 %> of <%= Model.TotalPages %></span>
<% } %>
<% if (Model.CurrentPage > 0) { %>
<% Html.BeginForm(); %>
<input type="submit" value="<<<" />
<input type="hidden" name="searchQuery" value="<%= Model.SearchQuery %>" />
<input type="hidden" name="page" value="<%= Model.CurrentPage - 1 %>" />
<% Html.EndForm(); %>
<% } %>
<% if (Model.CurrentPage < Model.TotalPages - 1) { %>
<% Html.BeginForm(); %>
<input type="submit" value=">>>" />
<input type="hidden" name="searchQuery" value="<%= Model.SearchQuery %>" />
<input type="hidden" name="page" value="<%= Model.CurrentPage + 1 %>" />
<% Html.EndForm(); %>
<% } %>
</div>
</div>
I keep getting an error: The name 'ForumViewHelper' does not exist in the current context. I am using the OpenForum dll. I called the Html.RenderPartial("Index.ascx").
I think the issue is that "ForumViewHelper" is a class inside the "OpenForum.Core.Views" namespace. Try using this instead...

asp.net mvc - How to find exactly which button was clicked when button names are all identical?

I've got the following code in my aspx file:
<% using (Html.BeginForm())
{
int i = 0;
%>
<% foreach (var item in Model.Educations)
{ %>
<fieldset>
<input type="hidden" name="educations.Index" value="" />
<p>
<label for="PID">
PID:</label>
<%= Html.TextBox("educations["+i+"].PID", item.PID)%>
<%= Html.ValidationMessage("PID", "*")%>
</p>
<p>
<label for="EducationType">
EducationType:</label>
<%= Html.TextBox("educations["+i+"].EducationType", item.EducationType)%>
<%= Html.ValidationMessage("EducationType", "*")%>
</p>
<p>
<label for="SchoolName">
SchoolName:</label>
<%= Html.TextBox("educations["+i+"].SchoolName", item.SchoolName)%>
<%= Html.ValidationMessage("SchoolName", "*")%>
</p>
<p>
<label for="UniversityId">
UniversityId:</label>
<%= Html.TextBox("educations["+i+"].UniversityId", item.UniversityId)%>
<%= Html.ValidationMessage("UniversityId", "*")%>
</p>
<p>
<label for="Department">
Department:</label>
<%= Html.TextBox("educations["+i+"].Department", item.Department)%>
<%= Html.ValidationMessage("Department", "*")%>
</p>
<p>
<label for="Degree">
Degree:</label>
<%= Html.TextBox("educations["+i+"].Degree", String.Format("{0:F}", item.Degree))%>
<%= Html.ValidationMessage("Degree", "*")%>
</p>
<p>
<label for="YearOfGraduation">
YearOfGraduation:</label>
<%= Html.TextBox("educations[" + i + "].YearOfGraduation", String.Format("{0:F}", item.YearOfGraduation))%>
<%= Html.ValidationMessage("YearOfGraduation", "*")%>
</p>
<p>
<label for="ID">
ID:</label>
<%= Html.TextBox("educations[" + i + "].ID", item.ID)%>
<%= Html.ValidationMessage("ID", "*")%>
</p>
<input type="submit" name="silButton" value="Sil"/>
</fieldset>
<%
i++;
} %>
<p>
<input type="submit" name="ekleButton" value="Ekle" />
</p>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
This way I'm able to dynamically add ("Ekle") more fields if user wants to enter additional education information (most probably from another university or another degree).
This code also give "Sil" button (which means delete), and I want to be able to detect exactly which "Sil" button was pressed and delete that Education entry from my "object" in session.
My action method looks like this:
public ActionResult Step3(string ekleButton, IList<Education> educations, IList<string> silButton)
{
if (educations != null)
{
_person.Educations.Clear();
_person.Educations.AddRange(educations);
}
if (ekleButton != null)
{
_person.Educations.Add(new Education());
}
if (silButton!=null){
//find index and delete it from _person.Edications
}
return View(_person);
}
In this way silButton != null if any of the "silButton" buttons was pressed and I can't detect which button was pressed. Is there a way to find this out?
You could put the index in the name of the button:
<input type="submit" name="silButton<%=i %>" value="Sil" />
And in your action method:
var silButton = Request.Params.AllKeys.FirstOrDefault(key => key.StartsWith("silButton"));
if (!string.IsNullOrEmpty(silButton))
{
var index = int.Parse(silButton.Replace("silButton", string.Empty));
}

Resources