Value not persisting on Submit with validation error - asp.net-mvc-3

I'm using MVC3 .NET4.0 (VB), and I'm seeing some strange behavior on a simple View. It's a Create view that is set up as:
Inherits="System.Web.Mvc.ViewPage(Of MyProject.MyTable)
The controller is pretty straightforward. It accepts the ID of the parent record to which this record is being added:
Function Create(parent As Integer) As ActionResult
Return View(New MyTable With {.parent_id = parent})
End Function
The View also accepts a date among other things, but it boils down to this:
<% Using Html.BeginForm()%>
<%=Html.ValidationSummary(True)%>
<%=Html.DisplayFor(Function(model) model.parent_id)%>
<%=Html.TextBoxFor(Function(model) model.start_date)%>
<%=Html.ValidationMessageFor(Function(model) model.start_date, "*")%>
<button type="submit" id="submitButton">Save</button>
<% End Using%>
I'm testing the handling of date errors, so right now my post controller is just checking for errors and not doing much else:
<HttpPost()>
Function Create(model As MyTable) As ActionResult
If ModelState.IsValid Then
Return RedirectToAction("Index")
Else
Return View(model)
End If
End Function
When I first load the view, I see the parent ID displayed on the form. If I put a bad date into the start date field and hit Submit, the form comes back with the invalid value highlighted, but the parent ID = 0. If I break the code in the post, I can see that "model" doesn't have the parent ID set. This obviously causes all kinds of problems, because I've essentially lost who the parent is. What am I doing wrong?
UPDATE
Per Darin's suggestion I changed DisplayFor to HiddenFor and didn't see any difference. So then I tried TextBoxFor and got stranger results. I still don't see the parent ID in the post function, but the value persists in the text box.

What am I doing wrong?
You are not including the parent_id as hidden field in your form. Inside your form you have a single input element which corresponds to the start_date field, so that's all that you can hope to get in your POST action.
So:
<%= Html.HiddenFor(Function(model) model.parent_id) %>
The DisplayFor that you used only displays the value, it doesn't emit any input field to transport this value to the server when the form is submitted.

Related

laravel update shouldn't do anything if no value changed

If I open a form to edit and without changing any value just hit Submit button to update, it updates the row in the table i.e. it changes the updated_at time and even executes some code in bootXXXX(static::saving(function($model) {}) function.
I do not want that to happen.
How can I find If user changed nothing and its a blank submit button hit?
Of course before update I can fetch the current values and compare them with input $request->all() and decide to update or not, but Is there any better way to do so the laravel way?
Thanks,
K
you have 2 methods one is getDirty() by using this you will get current changed input value, another one is getOriginal() if you use that you will get what previous data you have
By using those 2 methods i am giving here a example,may be it will help you
static::saving(function($model)
{
foreach($model->getDirty() as $attribute => $value){
$original= $model->getOriginal($attribute);
echo "Changed $attribute from '$original' to '$value'<br/>\r\n";
}
return true; //if false the model wont save!
});

How to add nested form field into current form dynamically?

I have a many to many relationship between Users and Chatgroups. Intuitively, Users can have many Chatgroups and each Chatgroup can have many users.
I've implemented this with a join table called UserChatGroup.
In my Chatgroup controller, when routed to the new function, I can hardcode the number of members in a chatgroup by specifying userChatGroups:[%UserChatGroup{},%UserChatGroup{}] etc, where the hardcoded number is the size of this array.
For example, my controller for a new chat group hardcodes 1 user:
def new(conn, _params) do
changeset = ChatGroup.changeset(%ChatGroup{userChatGroups: [%UserChatGroup{}]})
render(conn, "new.html", changeset: changeset)
end
and in my template for new, it references a form. The relevent section of the form is below:
<%= inputs_for f, :userChatGroups, fn i -> %>
<div class="form-group">
<%= label i, :user_id, "User Id", class: "control-label" %>
<%= number_input i, :user_id, class: "form-control" %>
</div>
<% end %>
However I'd like to remove this hardcoded number of members in the chat group. Instead I'd like the user to be able to add members dynamically.
I'm having trouble with this however. The rails way of doing this is to call a function that accesses the form object and updates it. Then insert input fields with javascript. On submitting, the new input fields would be fields for the new form object.
However I can't figure out how to do this with the Phoenix Framework.
My first question:
How do I define functions in my view.html.eex so that they can be called on click and not simply rendered immediately? Seems like when I try using <%= functionFromMyView %> the function is rendered on initial load of my page. I want to call this function when I click an 'add' button so I need to figure out how to call this function only on click. Is that possible?
Question 2, more specific to my use case:
How do I add %UserChatGroup{} dynamically to my form?
I'm assuming that once I can figure out how to call a function from my view on a click, then I can use that function to insert a %UserChatGroup{} to my form and then using javascript, insert an input field that connects to the newly inserted nested UserChatGroup field.
Any guidance would be greatly appreciated.
I wasn't able to add a %UserChatGroup{} to my form.
I believe this is because the web is HTML, CSS, and JS, whereas the above was Elixir.
Therefore I assume my solution must be javascript.
I examined the html on the page which told me the %UserChatGroup{} input field had a name name="chat_group[userChatGroups][0][user_id]"
chat_group is the name of the model I am creating,
userChatGroups is the array I created to handle the members of the chat group,
[0] is the index of the input array and can go as big as you want a group to be
user_id is the field in my join table.
The index is the only value you need to change.
With javascript, I inserted input fields within my form, with a name="chat_group[userChatGroups][--indexnumber--][user_id]" and when submitting, the form would naturally also submit my newly added input. (replace indexNumber)
This way can handle adding as many chat group users as I needed.

apex always execute validation

Is it possible to execute validations on page load regardless if it is submitted or just loaded?
I need to implement it for ordinary validations created in processing page section and for min max validations assigned to number field.
Is it possible to implement?
Indeed: having a server side validation will throw an error, but the page has submitted and thus the changed values are in session state. You could try to prevent this by having a plsql validation which would blank out the session state value when an error occurs, but might not be optimal. I think that some javascript could alliviate some of the trouble.
Here is some javascript that restricts the selectable ranges in the to and from datepickers. It won't allow a user to pick a larger from than to date, and vice versa. It also sets the item to readonly, so that the user has to select through the datepicker and can not alter it by hand.
Page > Javascript > Function and Global Variable Declaration
function f_check_date(){
var lFrom = $("#P6_DATE_FROM").datepicker("getDate"),
lTo = $("#P6_DATE_TO").datepicker("getDate");
if(lFrom > lTo || lTo < lFrom){
//in case it does happen
$("#P6_DATE_FROM").val('');
$("#P6_DATE_FROM").val('');
alert('Please select a valid date range.');
} else {
//when a date changes, the other datepicker has to be altered so the
//range is adjusted
$("#P6_DATE_FROM").datepicker("option","maxDate",lTo);
$("#P6_DATE_TO").datepicker("option","minDate",lFrom);
};
};
Dynamic Action, Page Load, Execute javascript
//on load, set the datepicker range in case a date is already present
//when the date changes, call the datecheck function
//and set item to readonly
$("#P6_DATE_FROM")
.datepicker("option","maxDate",$("#P6_DATE_TO").datepicker("getDate"))
.change(f_check_date)
.prop("readonly",true);
$("#P6_DATE_TO")
.datepicker("option","minDate",$("#P6_DATE_FROM").datepicker("getDate"))
.change(f_check_date)
.prop("readonly",true);

Showing a default value in a WebGrid when a null is present?

I've got Webgrid sourced to a EF4 entity with navigation properties (basically relationships)
If the webgrid encounters a null for that foreign key it errors out because it's looking for that object, which in this case doesn't exist.
Is it possible to catch when a column item is null and default to a value within the Webgrid helper?
I guess the follwoing code should serve your purpose if I am correctly relating to your problem. Below Trigger is the navigated entity which we will get by include in linq and we can put a check like below when this entity is null.
grid.Column("Job", format: #<text> #if (#item.Trigger !=null) { <span> Write your default code here .</span> } </text> close text tag here ),
Hope that solves your problem.
I noticed after posting 'text' is getting truncated in this forum so put text in < and > between 2 # as you can see and also close that text tag before the final ).
All the best.

Grails: can remoteField update multiple fields?

Assume i have a book entity with an isbn field.
When entered a isbn number, i want 2 fields to be updated: title and author.
My controller looks like this:
def ajaxGetBook = {
def book = Book.findByIsbn(params.isbn)
if(book==null) book = new Book()
render book as JSON
}
So my call works, and i get a full JSON Book.
Now i would like to update 2 texfields by the update attribute
<g:remoteField action="ajaxGetBook" update="title" name="isbn" value="${bookInstance?.book?.isbn}" paramName="isbn"/>
Now the title field gets updated with the full book object, so that doesn't work.
Is it possible to update field title with only the JSON book.title?
Is it possible to update more fields at once?
I could render book.title as JSON but that works for only one field.
Thank you
Well, the g:remoteField tag is explicitly for one field, so you can't use it to update more than one. So, you're left with 2 easy choices:
Use 2 g:remoteField calls... this isn't a bad option, as they would happen in near parallel, as they are Async calls.
Roll your own Ajax. use g:remoteFunction instead, and have the JS function that you place in the "success" attribute take your book, and update the appropriate HTML fields.

Resources