Showing a default value in a WebGrid when a null is present? - asp.net-mvc-3

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.

Related

Bootgrid hide column in jquery

Greeting, I would like to ask a question about the bootgrid jquery.
After I tried to understand the documentation of the bootgrid, I know that hiding a column are able to do in the column setting, <th data-visible="false">sampleID<th>, but I want to do this function inside jquery because I have a condition for displaying some column.
For example, I have three columns which is 'A','B','C'. So when the Listing value is 'A', the column B and column C will be set to data-visible = "false":
$('#Listing'.val()) == "a"
{
$('#B').attr("data-visible","false");
$('#C').attr("data-visible", "false");
}
So I have tried the code above but it not work. Please suggest me a solution or method.
Is it possible if I set the data-visible using the jquery?

Ckeditor getSelectedElement always null

I am trying to get the selected element in Ckeditor. I.e. if the html is:
This has a link.
I want to retrieve the entire a element when I select the link text.
As I understand it the following code:
editor.getSelection().getSelectedElement()
is supposed to do that. But it is always returning null (no matter how much or how little I select). I have tried various other element types and the result is always the same.
getSelection() by itself is not returning null. I am able to get just the link text with
editor.getSelection().getNative().toString().
I even tried some old code that I found here:
http://cksource.com/forums/viewtopic.php?f=6&t=11997&p=31833
but that resulted in the error Object #<Object> has no method 'getRangeAt'
Does anyone have any suggestions?
I was too troubleshooting the same thing. But got this code working.
Just check if it helps
var element = CKEDITOR.plugins.link.getSelectedLink( editor );
if ( element )
{
if ( element.is( 'a' ) )
{
var urldata = element.getAttribute( 'href' );
this.setValue(urldata);
}
}

Value not persisting on Submit with validation error

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.

EntityFramework attempting to insert null when asked to save a reference to an existing Entity in a new Entity

I'm using ASP.Net MVC3, and Entity Framework 4.
Employee has an OfficeLocation, which is in another table for normalization.
I have a new Employee screen, with a drop down for Office Location:
<div class="editor-label">
#Html.LabelFor(model => model.OfficeLocation.Id, "Office Location")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.OfficeLocation.Id, new SelectList(ViewBag.OfficeLocations, "Id", "Name"))
#Html.ValidationMessageFor(model => model.OfficeLocation.Id)
</div>
It points at the Id because I was having trouble getting the binding to work. In my controller, I load the OfficeLocation from the database, and store it back in my new Employee before saving. I've inspected the values at this point and everything is correct. I've also tried to Attach() employee.OfficeLocation, with no change. employee.OfficeLocation has no null values in it, and its state is Unchanged.
employee.OfficeLocation = db.OfficeLocations.Single(d => d.Id == employee.OfficeLocation.Id);
db.Employees.AddObject(employee);
db.SaveChanges();
And that's when I get an exception about inserting into OfficeLocations:
Cannot insert the value NULL into column 'Name', table 'test.HR.OfficeLocations'; column does not allow nulls. INSERT fails.
The statement has been terminated.
I've also tried the usual restarting Visual Studio, cleaning the build, et cetera.
Update: When I allowed null values, I found that it inserted a row into OfficeLocation with all null values, and then it used the correct value in the Employee table. What.
Don't use an Id when linking these two entities together. Just introduce an OfficeLocationtyped property in your Employee class, and link new office locations to your Employee instances whenever you create them. There is no need to have an over complexity by explicitly specifying an Id in your case.
This is what happens when you try to use your data model in your view. You really should be creating custom view models that are unique to your page, with only the data required on that page.
THen, you would simply do something like this:
employee.OfficeLocationID = model.OfficeLocationID
You don't set the OfficeLocation.ID, you set the ID in the employee entity. OfficeLocation is a navigation property that navigates to a record specified by the OfficeLocationID property of your employee.
The root cause of my problem was that in working around IModelBinder, I was causing something in the framework to generate new OfficeLocations that only contained an (existing) Id - which is ignored by EF when inserting, because I have it using SQL's Id generation. I worked this out by letting the columns be null and noticing that it correctly set the existing Id in the Employee table, while inserting a new, null-Named record into the other table.
So even though that new Entity was no longer referenced anywhere, the framework was trying to insert it when I saved the Employee entity that originally referenced it.
Hopefully someone else will benefit from this.

SqlDateTime overflow thrown by Typed DataSet Insert

I'm using a Typed DataSet with an Insert statement; I have a table that has a smalldatetime field defined to accept null values. When I insert from a .NET 2.0 FormView, I get a "SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM."
Now, I've read this post, and the parameter as sent to the class constructor is defined as
global::System.Nullable<global::System.DateTime> DoB
So, it looks like it should accept a Nullable obj. Additionally, the generated code is testing the value sent.
if ((DoB.HasValue == true)) {
command.Parameters[6].Value = ((System.DateTime)(DoB.Value));
}
else {
command.Parameters[6].Value = global::System.DBNull.Value;
}
Specifically, the error is occurring when generated SqlClient.SqlCommand.ExecuteScalar() runs:
try {
returnValue = command.ExecuteScalar();
}
So, I guess my question is: how do I use a Typed DataSet to set a blank value (passed from a FormView on CommandName=Insert) to a null in a database?
Ok, so here's what worked for me. First, to reiterate, I've got a Typed DataSet with DataAdapters that's generating the ADO objects. So, on my page, I can create a ObjectDataSource with the type that points to my adapter, and then name the different access methods housed there-in.
No, I have an Insert to a table where basically all the columns are nullable; some varchar, some smalldatetime.
When I submit an empty form, I'd like nulls to be entered. They're not and lots of various errors are thrown. What I ended up doing is subclassing the ObjectDataSource to gain access to the Inserting event. (subclassed for reusability) In the Inserting event, I looped through the InputParameters, and if it was a string and == "", I set it to null. Also, you cannot set ConvertNullToDBNull to true; that causes the strings to fail. This successfully allowed the Nullable to remain null.

Resources