سؤال

I have model with a property of string type. I bind this model to view (razor view) and bind this property to hidden field. The property has value as blank (String.Empty).

When I post model to controller, the value what I get is null instead of blank.

Any idea?

هل كانت مفيدة؟

المحلول 2

If you are trying to preserve null values as nulls and empty strings as empty strings for a round-trip operation, perhaps you could define a special constant string value to denote null. Perhaps something like this in a static class (so you can make an extension of it):

private const string NULL_STRING = "__@NULL@__";

public static string StringifyIfNull(this string s) {
  return s == null ? NULL_STRING : s;
}

public static string DestringifyIfNull(this string s) {
  return NULL_STRING == s ? null : s;
}

So, when setting the hidden string properties on your model, use hiddenString.StringifyIfNull(), and when reading back the hidden values after a POST, use model.HiddenString.DestringifyIfNull()

نصائح أخرى

Add [DisplayFormat(ConvertEmptyStringToNull = false)] to your class markup.

That is what the MVC framework does when it maps request data to controller parameters, and the request data is an empty value. If you check the value in the Request.Form collection, you will see that it actually is an empty string there, not a null value.

You can either handle the null values that the framework generates, or read the data from the Request.Form collection.

This link should be helpful.

Why do I get null instead of empty string when receiving POST request in from Razor View?

"The default model binding will create a new SomeModel for you. The default value for the string type is null since it's a reference type, so it's being set to null." Original answer by statichippo

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top