开发者

Strange Model Binder behavior with fractional number

I am confused by strange model binder behavior:

- when I use RedirectToAction with parameters which includes fractional number (because in Russian, we use "," instead of ".", e.x. 1,5; 2,5) in View it Binds that with dots, "4,5 => 4.5", and after post form I have ModelState error and values equal to 0. When inputting integer numbers however, all works as expected.

How i can fix it?

Models:

public class TestA
{
    public double FirstNumberA { get; set; }
    public double SecondNumberA { get; set; }
}

public class TestB
{
    public double FirstNumberB { get; set; }
    public double SecondNumberB { get; set; }
}

controller:

public ActionResult Index()
{
    return View();
}
[HttpPost]
public ActionResult Index(TestA model)
{
    return RedirectToAction("About", new { firstNumberB = model.FirstNumberA, secondNumberB = model.SecondNumberA });
}

public ActionResult About(double firstNumberB, double secondNumberB)
{
    return View(new TestB() { FirstNumberB = firstNumberB, SecondNumberB = secondNumberB });
}

[HttpPost]
public ActionResult About(TestB model)
{
    return View();
}

views: /* index */

@model TestA
@using (Html.BeginForm())
{
    @Html.TextBoxFor(x => x.FirstNumberA)
    @Html.TextBoxFor(x => x.SecondNumberA)
    <input type="submit" name="submit" value="submit" />                                            
}

/* about */

@model TestB
@using (Html.BeginForm())
{
    @Html.TextBoxFor(x => x.FirstNumberB)
    @Html.TextBoxFor(x => x.SecondNumberB)
    <input type="submit" name="submit" value="submit" />
}

Upd When remove TextBoxFor(x => x.SecondNumberB) in About.cshtml and post form - FirstNumberB will cause an ModelState error, when SecondNumberB binds as should.

Upd2 I think, that here is another problem, that describe Phil Haack in his post - asp.mvc first look for values at the query string and get it. And in my case in query string I have ?firstNumber=1.5 and it binds to TextBox "as-is", without culture rules. And after post we get FormatException error. How can I fix it - bind decimal values to textboxes with correct culture decimal-separators? I can't use any JavaScript. I think about workaround with TempData before ReturnToRe开发者_如何学Cdirect, but in this case user can't reload the page.


Could be a culture problem. Make sure you set the correct culture in your web.config <globalization> element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜