check nullable value object in razor view - asp.net-mvc

I wanna check a string nullable value. But its not work? Plz, someone show me how?
<%= LDC.Helpers.DataHelper.GetLabel(LDC.Helpers.DataHelper.getTypeMaxGrossWU(), (int)item.MGW_unit) != null ? LDC.Helpers.DataHelper.GetLabel(LDC.Helpers.DataHelper.getTypeMaxGrossWU(), (int)item.MGW_unit): "" %>

Assuming GetLabel returns null your code should work, so it appears it does not return null. Check the function's return type to see what equality check you should use.
Also, it's worth saying that this kind of logic should be put into a ViewModel. Putting it into your view is dangerously close to having spaghetti code.

Related

MVC how to check for NULL in model.property

In a razor-view, how can I check the existence of a property in a model?
if (Model._myProp != null) <--- error .RuntimeBinder.RuntimeBinderException if Model does not contain _myProp
{
...do something
}
You do not want to check that one of the model's properties has the value null you want to check the type for it is having a property or not and ofcourse you solution will not work that way but #Satpal's wont work too.
Use stronly typed views and separate different properties into interfaces and use them with partial views.

ASP.NET MVC 3 HtmlHelper.Textbox Uses ModelState as a source for value?

I have a textbox that I am trimming the value of server side in the viewModel's setter and verifying that the trimmed value is present:
<Required()>
Public Property Name As String
Get
Return Me.mName
End Get
Set(value As String)
Me.mName = value.Trim()
End Set
End Property
In the controller, I check to see if the ModelState is invalid, and if it is, I show the view again:
If (Not ModelState.IsValid) Then
Return View("Locations", viewModel)
End If
In situations where the trimmed value is blank, I re-display the form to the user. At this point, the non-trimmed values are put into the textbox. I would much prefer the trimmed value.
I was looking through the MVC sourcecode, and I found that at one point in the InputHelper function (used by Html.Textbox(), located in InputExtensions.cs) the code was checking the ModelState for the value, and if it existed, replacing the controller-supplied value.
string attemptedValue = (string)htmlHelper.GetModelStateValue(name, typeof(string));
tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(name) : valueParameter), isExplicitValue);
I realize that I could fix this by clearing the ModelState in the controller, but I'm just wondering why the MVC Developers chose to have the values in the ModelState supersede the view model values.
This was designed this way because the assumption is if you are not redirecting to another view after a post .. Hence the post-redirect-get pattern, then there was ideally an error and the current posted values would be shown back to the user for them to fix hence why they are pulled from modelstate. You can ModelState.Clear to work with this but keep that design in mind.

What is the correct pattern to protect against NullReferenceExceptions in ASP.NET MVC

UPDATE
The issue was a syntax issue. #awrigley shows the correct way to write this in Razor.
The following works:
#if(Model.Thing.Prop != null)
{
Html.RenderPartial("SomePartialView", Model.Thing.Prop);
}
You have a requirement to show details for the top 1 Foo for a given Bar as an HTML table. How do you hide the empty table or show a "none found" message if that Foo is null?
For example. I'm getting a NullReferenceException on the following line because Model.Thing.Prop is null;
#{Html.RenderPartial("SomePartialView", Model.Thing.Prop);}
It is intentionally null, my Repository returns null instead of a empty Foo. But this is mildly beside the point, which is that given a null Model.Thing.Prop, I don't want to call the Html.RenderPartial.
Update
I've tried the following with no luck:
#if(Model.Thing.Prop != null)
{
#{Html.RenderPartial("SomePartialView", Model.Thing.Prop);}
}
Which results in Visual Studio telling me it's expecting a ; at line 1, column 1 and also that ; is an Invalid expression at line 1, column 1 (I'm guessing this is due to the pre-release status of MVC3), and if I hit the page in a browser I get
CS1501: No overload for method 'Write' takes 0 arguments
with the #Html.RenderPartial line highlighted.
I also tried
#if(Model.Thing.Prop != null)
{
<text>
#{Html.RenderPartial("SomePartialView", Model.Thing.Prop);}
</text>
}
but this results in a NullReferenceException from within my Partial View, which doesn't seem right. Model.Thing is definitely a valid Bar and Model.Thing.Prop is definitely a null Foo.
I presume you don't want to use...
#if (Model.Thing.Prop != null)
{Html.RenderPartial("SomePartialView", Model.Thing.Prop);}
...because you still want to render part of the partial view?
Oh, no. Have read your post properly.
I have no idea why the above code doesn't work for you.
EDIT:
Remember that in Razor, # can be used two ways:
To execute statements:
#{
MyStatement;
}
To evaluate an HtmlHelper, a class method, property or variable that returns a string of some form or other (eg, HtmlString, MvcHtmlString or string). For example:
#MyClass.MyStringProperty
Note that in case 2, no terminating semi colon is required.
1 and 2 indicate that if you have an htmlhelper that returns something other than a string (eg, void), then you have to call it as follows:
#{Html.MyHelperThatReturnsVoid;}
Whereas with an HtmlHelper that returns a string or HtmlString or MvcHtmlString, you can simply write:
#Html.MyHelperThatReturnsAString
For more detail, see the accepted answer to a question I asked:
Custom HtmlHelper that returns void problem
This is either a change in MVC3 or something odd.
MVC2 Behavior:
If Model.Thing is null, then yes it is a null ref exception.
If Model.Thing exists and Thing.Prop is null, then you'll pass a null reference to model. When you pass a null ref to model, parent model (the Model here) gets passed as the model to "SomePartialView" which would be expecting type Prop (unless Model and Prop are the same type).
Considering you're getting null ref, I'm going to assume that Model.Thing is null. In that case your only solution would be an #if statement. Passing null into a model ref simply doesn't work and I've torn some hair out over the behavior.
Again, this is MVC2 behavior, if this has change for MVC3 where you honestly can pass a null model, awesome!

How to check null value in MVC view?

I am using MVC with LINQ-to-SQL class.
as foreign key can be null, i have one record having f.k. null and others are having values.
now i am displaying it in view by Index view.
In index view i am resolving f.k. by writing code like
<%= Html.Encode(item.UserModified.UserName) %>
Now i have a problem in view that "object reference is not set".
And this is because of we are having null value in one of the f.k. field!
so can i write code in view to check whether Associated object pointing to null or nothing?
You can write any code you want in the view if necessary, so you could do:
<%= Html.Encode(item.UserModified.UserName ?? string.Empty) %>
You could also make a HtmlHelper extension to do this:
public string SafeEncode(this HtmlHelper helper, string valueToEncode)
{
return helper.Encode(valueToEncode ?? string.Empty);
}
You could then simply do:
<%= Html.SafeEncode(item.UserModified.UserName) %>
Of course if it's UserModified that's null and not UserName then you'll need some different logic.
With C#, you can use the conditional operator:
<%= Html.Encode(item.UserModified == null ? "" : item.UserModified.UserName) %>
However, it might be a better choice to move the UserName property to be a direct child of item, or to put it in ViewData.
First consider whether in your model an instance of User is valid without Name. If no then you should put a guard clause in the constructor.
Secondly, too many and duplicated null checks is a code smell. You should use the refactoring Replace Conditional with Polymorphism. You can create a Null object according to the Null Object Pattern.
This will make sure that you do not have to check for Null everywhere.

MVC - How to change the value of a textbox in a post?

After a user clicks the submit button of my page, there is a textbox that is validated, and if it's invalid, I show an error message using the ModelState.AddModelError method. And I need to replace the value of this textbox and show the page with the error messages back to the user.
The problem is that I can't change the value of the textbox, I'm trying to do ViewData["textbox"] = "new value"; but it is ignored...
How can I do this?
thanks
You can use ModelState.Remove(nameOfProperty) like:
ModelState.Remove("CustomerId");
model.CustomerId = 123;
return View(model);
This will work.
I didn't know the answer as well, checked around the ModelState object and found:
ModelState.SetModelValue()
My model has a Name property which I check, if it is invalid this happens:
ModelState.AddModelError("Name", "Name is required.");
ModelState.SetModelValue("Name", new ValueProviderResult("Some string",string.Empty,new CultureInfo("en-US")));
This worked for me.
I have a situation where I want to persist a hidden value between POST's to the controller. The hidden value is modified as other values are changed. I couldn't get the hidden element to update without updating the value manually in ModelState.
I didn't like this approach as it felt odd to not be using a strongly typed reference to Model value.
I found that calling ModelState.Clear directly before returning the View result worked for me. It seemed to then pick the value up from the Model rather than the values that were submitted in the previous POST.
I think there will likely be a problem with this approach for situations when using Errors within the ModelState, but my scenario does not use Model Errors.

Resources