Skip to content Skip to sidebar Skip to footer

Mvc: How To Fix Null Value From Httppost When Formatting Punctuation(decimal?, Nb-no)?

When I send the form from client side I can see that Nap.GetUp has a value. However when debugging I see that the controller has not gotten a value for Nap.GetUp. I don't know wher

Solution 1:

You haven't given us your view model but I think it should be something like this

publicclassNapViewModel
{
    publicint  PeriodId { get; set; }
    publicdecimal? GetUp { get; set; }
    // other fields
}

Remove the

@{
string getUpValue = (Model == null) ? null : Model.GetUp.ToString().Replace(",",".");
}

from the view, razor is the wrong place to do this and in this case is the reason you are having this problem. Then your form code should be this

@using (Html.BeginForm())
{
    @Html.LabelFor(m => m.GetUp, new { @class = "" })
    @Html.TextBoxFor(m => m.GetUp, new { @type = "number", @step = "0.1", @class = "form-control" })

@*other form elements*@
}

Then put all the code for populating the viewmodel into the controller. I.e. transform what comes from the database for GetUp into a decimal. And then the model binding will just work as you expect. Then when the data comes back to the controller you will need to change the GetUp value to an appropriate form so that you can save to it your database.

Edit:

The problem is to do with culture. The controller is expecting the double to have a , but instead it has a full stop (period). The solution is a custom model binder.

Add this class to your project

publicclassDoubleModelBinder : DefaultModelBinder
{
    publicoverrideobjectBindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult == null)
        {
            returnbase.BindModel(controllerContext, bindingContext);
        }
        returndouble.Parse(valueProviderResult.AttemptedValue, System.Globalization.CultureInfo.InvariantCulture);           
    }
}

Then add this to your Global.asax

protectedvoidApplication_Start()
        {
            //other application_start code goes here

            ModelBinders.Binders.Add(typeof(double?), new DoubleModelBinder());
            ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder());
        }

Then to make sure your getup value appears in the text box change the getup textbox code to

@Html.TextBoxFor(m => m.GetUp, new {
    @type = "number",
    @step = "0.1",
    @class = "form-control",
    @Value =Model.GetUp.ToString().Replace(",",".") })

Post a Comment for "Mvc: How To Fix Null Value From Httppost When Formatting Punctuation(decimal?, Nb-no)?"