Note that there are some explanatory texts on larger screens.

plurals
  1. POASP MVC 3: Client Validation not working properly when submitting a form using AJAX
    primarykey
    data
    text
    <p>I have the following scenario, I have a for that I'm submitting using ajax using the following code:</p> <pre><code>$("#cmdAjaxSave").click(function (evt) { evt.preventDefault(); var $form = $('#frmItem'); if ($form.valid()) { ajaxSave(); } }); function ajaxSave() { if (!onBeforeSubmit()) return; //item is not valid, so the ajax call should not be executed //var token = $('[name=__RequestVerificationToken]').val(); popup('ajaxSplash'); $.ajax({ type: "POST", url: '@Url.Action("Index")', data: $("#frmItem").serialize(), success: function (html) { //console.log(html); $("#formDiv").empty(); $("#formDiv").append(html); initItemPage(); alert("Item was saved successfully"); }, error: function () { popup('ajaxSplash'); onFailure(); } }); } </code></pre> <p>The problem I'm seeing here is that even though "frmItem" is returning "true" when I arrive clientside the ModelState is not valid. Specifically for three properties, which actually has the correct value.</p> <p>Digging into the code made by the developer who originally coded this I found that for instance this property:</p> <pre><code>@Html.TextBoxFor(model =&gt; model.Item.Service.CPC_BW, htmlAttributes: new { @class = "Text", @onkeyup = "validItem();", @id = "SrvCPCBlk" }) </code></pre> <p>Is actually defined like this:</p> <pre><code>private double _CPC_BW; [Required] [Range(0, 100000, ErrorMessage = "CPC value required")] public string CPC_BW { get { return String.Format("{0:F}", _CPC_BW); } set { _CPC_BW = Convert.ToDouble(value); } } </code></pre> <p>I think he did it because TextBoxFor does not offers an obvious way to format a number and even though it looks fishy I don't know how could this be causing the error.</p> <p>The Html of the form is rendered like this</p> <pre><code>&lt;div id="itemPopUpForm"&gt; @{Html.EnableClientValidation();} &lt;div id="formDiv"&gt; @{ Html.RenderPartial("ItemData", Model, new ViewDataDictionary() { { "Machines", ViewBag.Machines }, { "WarehouseList", ViewBag.WarehouseList }, { WebConstants.FORM_ID_KEY, @ViewData[WebConstants.FORM_ID_KEY] } }); } &lt;/div&gt; &lt;/div&gt; </code></pre> <p>The partial view contains the form that is submited in the ajax request.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload