I'm trying to pass a null value in a JSON object let's say: { 'property': null } to a controller action in ASP.Net MVC but in the action method I see the property gets a zero value instead of null.
What can I do about this?
just dont send that property or delete that in the client-side : delete x.yourProperty
for example if you have some .net mvc controller with a nullable property like this:
public JsonResult SomeAction(decimal? yourProperty){ //your code goes here }
if in the client-side you call some ajax request with yourProperty: null the model binder will set it to 0, like as int or string that will be set to EmptyString
so if you want to send it as null you just avoid sending it, or if it's a property that you have set before all you need is to just delete that property: delete x.yourProperty
The property on your model should be a nullable decimal if you want this to work:
public decimal? MyProperty { get; set; }
Related
I was looking at https://stackoverflow.com/a/15873977 but it didn't work for me.
If my Post method has a parameter named Message (an object of my own class), and I do not apply the [FromBody] attribute to it, is it possible to pass the parameter Message, json serialized and urlEncoded, on the query string instead of in the Post body?
I tried passing ?Message=%7B+%22Sender%22%3A...+%7D (which if decoded would be Message={ "Sender":... }) but the Message parameter is still received as null in the method.
Should the query string key be Message, the name of the parameter, or the class name of the parameter or something else?
If you have a model Foo:
public class Foo
{
public string Bar { get; set; }
public int Baz { get; set; }
}
And you want to bind this from the query string, then you must address the individual properties:
?Bar=qux&Baz=42
And annotate that the model must be bound from the query string:
public void Bar([FromUri]Foo foo)
{
}
If you really want to send JSON into your action method and not a model, simply bind to a string instead of a model. You can then do whatever you want with the JSON string inside your action method.
How to add a query string from surface controller in umbraco mvc . This is my current code.
Initially I wrote a code like
public ActionResult Registration(RegisterModel model)
{
//Code to insert register details
ViewBag.Success="Registered Successfully"
return CurrentUmbracoPage();
}
with this I could successful persist my ViewBag and model properties value but I could not add a query string with it.
For certain requirement I have to change the code that returns a url with querystring.
which I did as below
public ActionResult Registration(RegisterModel model)
{
//Code to insert register details
ViewBag.Success="Registered Successfully"
pageToRedirect = AppendQueryString("success");
return new RedirectResult(pageToRedirect);
}
public string AppendQueryString(string queryparam)
{
var pageToRedirect = new DynamicNode(Node.getCurrentNodeId()).Url;
pageToRedirect += "?reg=" + queryparam;
return pageToRedirect;
}
and with this my values of the properties in model could not persist and the ViewBag returned with null value.
Can any one suggest me how to add query string by persisting the values in the model and ViewBag.
Data in ViewBag will not be available on the View when it redirects. Hence you have to add message in TempData which will be available in the View after the redirect like TempData.Add("CustomMessage", "message");
I am using Entity Framework 4.0, and making use of POCO objects. When I populate POCO objects from the DB, I translate property values to my own Domain objects, which we can call my Model.
Necessarily, whether or not the fields of my Model are Nullable depends on whether the value it maps to in the database comes from a NULL or NOT NULL column. I won't go into detail, but the values must be nullable in the DB, because a user can partially save a draft of the object before publishing it to the public. That being the case, I have several fields that are nullable. So let's say my model looks like:
public class MyModel
{
public int? Field1 {get; set; }
public DateTime? Field2 {get; set; }
public int Field3 {get; set; }
}
If I use this Model in my View, complete with nullable fields, I begin receiving errors that tell me I cannot use nullable properties as values in various places, like HTML helpers, etc. I could say something like if (Model.MyBoolField.HasValue && Model.MyBoolField.Value) { // etc }, but that feels bulky for a view.
I considered creating a ViewModel object that inherits from my original domain object and has new, non-nullable versions of my nullable fields that return an appropriate value if the base version is null. So something like:
public class MyViewModel : MyModel
{
public new int Field1
{
get { return base.Field1 ?? 7; }
}
public new DateTime Field2
{
get { return base.Field2 ?? DateTime.Now; }
}
}
My problem with this is that I don't always know a good "default" value to display. What if I threw an exception in the View Model's getter when the base value is null? Is that poor practice?
I'm basically looking for a best practice on how to handle nullable fields in a model, particularly when displaying in a View.
If you just need to display these fields in a View, you don't need to specify or check whether is has a value or not.
Using Model.Field1 in your View file is enough. It will simple not display anything, and it won't throw an exception. You can always use ?? to set a default when it makes sense.
#(Model.Field1 ?? "There is nothing to see here")
In most of the cases I use the "For" helpers, which seem OK with Nullable values (PublishedCount is a nullable property):
#Html.TextBoxFor(m => m.BillPull.PublishedCount, new { id="txtPublishedCount" })
#Html.ValidationMessageFor(m => m.BillPull.PublishedCount)
When I need to use just TextBox, I use the GetValueOrDefault method, with whatever default value the framework provides:
#Html.TextBox("BillPull.AutoPublishDate", Model.BillPull.AutoPublishDate.GetValueOrDefault().ToString(dateFormat), new { id = "dtpAutoPublishDate" })
#Html.ValidationMessageFor(m => m.BillPull.AutoPublishDate)
I have a column in the database which is Name its string with null value.
when I dont enter anything in the Name Field its saving to the database as NULL.
but I need to save this value as string.Empty or "".
I did soemthing like this.
h.assignedName= m.Name== null ? string.Empty : m.Name;
ViewModel Property has
Public string Name {get;set;}
my question is any other way we can assign this value has String.Empty without doing any condition like above?
I dont want to use ? operator to check the condition or if condition.
Thanks
You could change the column in the database to not be NULL and set the default value to ''. That way you would not have to use the ? conditional. Not sure if this is best practise, but it would save you having to add additional code to cater for it.
The other way is to create a wrapper class around the data. I see you're using m.Name in your code example. You could have:
public class MyWrapper
{
private string _name;
public string Name
{
get {
if (String.IsNullOrEmpty(_name)){
return String.Empty;
}
return _name;
}
set{
_name = value;
}
}
}
So when you're reading the data from the database, create an instance of your wrapper class to hide the details when getting the Name.
Jason's idea is sound assuming you do not care about making that minor change.
Another way you could do it is to abandon your automatic property and handle the checking in the get
private string name;
public string Name
{
get { return (name == null) ? string.Empty : name; }
}
This obviously has more initial code over head for all properties that you want to utilize this style.
or you could ensure it is never null in your constructors
You might consider changing the layout of your code construction and use a business rule like
"m.Name may never be null." And then you should initialize it as String.Empty, so that it can never be null.
Is ther any way to pass a non static value to a actionfilter parameter like below?
public class ProcuctController : Controller
{
private int userID = 1;
[TestFilter(x=userID)]
public ActionResult Index()
{
}
}
No, there isn't. Attributes are baked into the metadata of the resulting assembly and all values should be known at compile time. You can pass only constant values as attribute properties. And that's .NET limitation, not MVC.
depending on the situation, you could always pass in some kind of key to the filter, and then inside the filter you could do a lookup for the corresponding value in whichever datasource you prefer. this would allow you to get non-static data in your method, though it would be nice if it were as simple as your example :-)
You can't pass it in but you could do something like:
public class TestFilterAttribute : ActionFilterAttribute
{
public string UserId
{
get
{
return AppSettings["UserId"];
}
}
}