I would like a form containing criteria fields. These criteria can be of type "affaire" or "suite". For this choice, I use a dropdownlist (see screenshot below). Based on this type, I would like to display only specific criteria fields.
For the type "affaire", I have the following criteria:
Statut affaire
Libellé affaire
Numéro d'affaire
Titre de l'affaire
Note de l'affaire
For the type "suite", I have the following criteria:
Statut suite
Libellé suite
Numéro de suite
Titre de la suite
Note de la suite
At this moment, I only display "affaire" criteria fields in my form. Something like this:
#using (Html.BeginForm("SearchAffaires", "Search", FormMethod.Post)) {
#Html.LabelFor(m => Model.SearchType)
#Html.DropDownListFor(m => Model.SearchType, Model.Type)
#Html.LabelFor(m => Model.SearchCriteriaAffaire.IdAffaire)
#Html.TextBoxFor(m => Model.SearchCriteriaAffaire.IdAffaire)
#Html.LabelFor(m => Model.SearchCriteriaAffaire.IdStatus)
#Html.DropDownListFor(m => Model.SearchCriteriaAffaire.IdStatus, Model.Status)
#Html.LabelFor(m => Model.SearchCriteriaAffaire.Title)
#Html.TextBoxFor(m => Model.SearchCriteriaAffaire.Title)
<input type="submit" id="buttonSubmit" value="Submit" />
<input type="button" id="buttonClear" value="Clear" />
}
The first DropDownListFor(...Model.Type) is used to distinguish the search of type "affaire" or "suite". I would like to be able to hide "affaire" criteria fields and show "suite" criteria fields based on the value of this dropdown. What is the best way to achieve this?
Thanks.
I'd probably just use a client-side event handler and toggle the elements' visibility..
$('#searchType').change(function() {
var value = $('#searchType option:selected').val();
if (value === 'affaire') {
$('.affaireCriteria').show();
$('.suiteCriteria').hide();
}
else {
$('.affaireCriteria').hide();
$('.suiteCriteria').show();
}
});
Just sample code.. there's plenty more you can do to make this more elegant.
Related
I'm iterating my Model.Payments collection (which is an public IEnumerable<Payments> Payments { get; set; }):
#using (Html.BeginForm())
{
<div class="payments">
#foreach (var payment in Model.Payments)
{
Html.RenderPartial("_Payment", payment);
}
</div>
<input type="submit" value="Aggiorna" />
}
And this is my _Payment partial:
#model MyProject.Models.Payments
<div class="payment-row">
<span>ActivityID:</span> #Html.TextBoxFor(x => x.ActivityID)
<span>PaymentType:</span> #Html.TextBoxFor(x => x.PaymentType)
<span>Amount:</span> #Html.TextBoxFor(x => x.Amount)
</div>
But it doesn't create a proper HTML. Name/ID are the same, so once I postback, I can't retrieve data.
Where am I wrong?
The correct approach is to use the EditorFor() method, which will correctly prefix your inputs with the collection indexer
Rename you partial view to Payments.cshtml (to match the name of the class), and move it to the /Views/Shared/EditorTemplates (or /Views/YourControllerName/EditorTempatesFolder)
Then you view becomes
#using (Html.BeginForm())
{
<div class="payments">
#Html.EditorFor(m => m.Payments)
</div>
<input type="submit" value="Aggiorna" />
}
The EditorFor() method generates the correct html for each item in the collection, and will generate inputs such as <input name="Payments[0].ActivityID" ... /> rather than <input name="ActivityID" ... /> which you are currently generating.
As a side note, you should consider using #Html.LabelFor() to generate a <label> associated with your form controls, rather than using a <span>.
I'm currently developing an app with Sinatra, ActiveRecord and MySQL. I'm working on the sign up form, which looks like this:
app.rb:
post '/signup' do
password_salt = BCrypt::Engine.generate_salt
password_hash = BCrypt::Engine.hash_secret(params[:password], password_salt)
#usuarios = User.new(params[:nombre], params[:cedula], password_hash, "admin")
if #usuarios.save
redirect './signup', :notice => "Usuario creado exitosamente."
else
redirect './signup', :error => "Ha ocurrido un error, intente nuevamente."
end
end
And the view looks like this, signup.erb:
<form id="registro" action="/signup" method="POST">
<fieldset>
<legend>Ingrese sus datos</legend>
<label>Nombre
<input type="text" name="nombre">
</label>
<label>Cédula
<input type="text" maxlength="10" name="cedula">
</label>
<label>Contraseña
<input type="password" name="password">
</label>
<!-- TO-DO:
Dropdown list con los diferentes tipos de usuarios, i.e.: admin, secretario, etc.
-->
<input type="submit" id="registerButton" class="button small">Finalizar registro</a>
</fieldset>
</form>
Whenever I try to create a new user, I get the following error:
ArgumentError - wrong number of arguments (4 for 0..2)
Considering that the table I'm trying to insert the values has 4 columns, I don't understand why I'm getting this error.
Any insight to help me solve this inconvenience would be greatly appreciated!
Thanks in advance.
ActiveRecord::new method allows only 2 parameters as arguments, it should be a hash. fix:
User.new(params[:nombre], params[:cedula], password_hash, "admin")
to:
User.new(nombre: params[:nombre], cedula: params[:cedula], password: password_hash, role: "admin")
You should always check the documentation, in 99% cases you can find a problem:
New objects can be instantiated as either empty (pass no construction
parameter) or pre-set with attributes but not yet saved (pass a hash
with key names matching the associated table column names). In both
instances, valid attribute keys are determined by the column names of
the associated table – hence you can’t have attributes that aren’t
part of the table columns.
new(attributes = nil, options = {})
Examples:
# Instantiates a single new object
User.new(:first_name => 'Jamie')
# Instantiates a single new object using the :admin mass-assignment security role
User.new({ :first_name => 'Jamie', :is_admin => true }, :as => :admin)
# Instantiates a single new object bypassing mass-assignment security
User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)
My project is Room-reservation service .I have View :
#model Client
#using (Html.BeginForm("SaveUserDB", "Booking", FormMethod.Post))
{
<div class="editor-label">
#Html.Label("Surname")
#Html.TextBoxFor(model => model.Surname)
</div>
<div class="editor-label">
#Html.Label("Name")
#Html.TextBoxFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.Label("Patronymic")
#Html.TextBoxFor(model => model.Patronymic)
</div>
<input type="submit" id="submit" value="Reservation" />
And I have controller for this View:
[HttpPost]
public ActionResult SaveUserDB(Client client)
{
if (ModelState.IsValid)
{
using (db)
{
db.Client.Add(client);
db.SaveChanges();
return RedirectToAction("Thankyou");
}
}
return View(client);
}
This controller save data client to database table Client. But I need also create record in second table Reservation, which takes parameters: Datetime.Now , and Client.Id. Parameter Client Id in database is autoincrement, but doesn't display in the View.
Well, if this is how you add a record to the Client table:
db.Client.Add(client);
Then why not use that same exact approach to add a record to the Reservation table? Something like this:
var reservation = new Reservation
{
ClientID = client.ID,
SomeOtherColumn = DateTime.Now
};
db.Reservation.Add(reservation);
(Note: This is based on speculation of what your Reservation object/table might look like based on your description. But the concept is the same. Create an instance of a reservation object and add it to the data context.)
I use the kendo ui mvc grid.
I set the columns to Editable(false);
I can still edit those fields in the popup editing dialog. Why?
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.FirstName).Editable(false);
model.Field(p => p.LastName).Editable(false);
}
)
Popups always has to be customized.
In Views > Shared > EditorTemplates > Person (or whatever your class is) you just toss in whatever you want
#model TelerikMvcApp1.Models.Foo.Person
<div>
#Html.HiddenFor(person => person.Id)
<div class="editor-label">
<label for="Title">First Name</label>
</div>
<div class="editor-field">
#Html.Kendo().TextBoxFor(person => person.FirstName)
</div>
</div>
When i am adding form to view & specifying parameters as
<?= $form->field($model, 'form_name', ['options' => ['id' => 'formName', 'name' => 'formName']])->textInput(); ?>
But, when i run in the browser & check for view page source, there it shows me
<input type="text" id="submitform-form_name" class="form-control" name="SubmitForm[form_name]">
this disturbs my javascript calling for field input. How to stop yii2 from generating its own id???
You are passing options to ActiveField. If you want override id and name attributes, pass them in textInput() options like so:
<?= $form->field($model, 'form_name')->textInput(['id' => 'formName', 'name' => 'formName']) ?>
Generated html output will be:
<input type="text" name="formName" class="form-control" id="formName">
Note that after that client validation for this attribute will stop working and that attribute won't be massively assigned.