使用Ajax Post

时间:2016-11-24 10:05:57

标签: ajax asp.net-mvc validation unobtrusive-validation

这是我的第一个asp.net mvc项目,我正在尝试构建一个显示countries列表的视图。在double click上,它将输入从readonly更改为false以启用编辑,并在keypressblur上保存更改。

现在,server-side validation正在运作,client-side却没有。我不确定是因为我没有表格标签,或者无法完成或需要手动连接。

CountryModel:

public class Country
{
    [Key]
    public int CountryId { get; set; }

    [Required]
    [MinLength(4)]
    [MaxLength(60)]
    [RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
    public string Name
    { get; set; }

}

国家控制人员行动:

    [HttpPost]
    public ActionResult Save(Country country)
    {
        if (ModelState.IsValid)
        {

            db.Entry(country).State = EntityState.Modified;
            db.SaveChanges();

            //return
            return Json("Success");
        }
        else
        {
            //return
            return Json("Failed");
        }
    }

国家/地区视图:

@model IEnumerable<Models.Country>

<h2>Manage Countries</h2>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            Options
        </th>
        <th></th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.EditorFor(modelItem => item.Name, new { htmlAttributes = new { @class = "grid-input", data_input_mode = "read", data_model_id = item.CountryId } })
                @Html.ValidationMessageFor(modelItem => item.Name, "", new { @class = "text-danger" })
            </td>
        </tr>
    }

</table>

scripts.js中

$(document).ready(function () {
    $(".grid-input").attr("readonly", true);

    $(".grid-input").dblclick(function () {
    var elem = $(this);

    if (elem.attr("data-input-mode") == "read") {
        elem.attr("data-input-mode", "edit");
        elem.removeAttr("readonly");

        //Remove selection when mode changes from read to edit only
        var sel = window.getSelection();
        sel.removeAllRanges();

        //bind blur and keypress to attempt saving data on focusout or enter press
        elem.on("blur keypress", function (e) {

            if (e.keyCode == 13 || e.type == "blur") {

                //Stop Bubbling
                e.stopImmediatePropagation();

                //Enable Readonly To Avoid Edits While Saving
                $(this).attr("data-input-mode", "read");
                $(this).attr("readonly", "true");

                //Get Country ID & Name
                var _countryId = $(this).attr("data-model-id");
                var _countryName = $(this).val();

                //Validate
                $.ajax({
                    url: '/Country/Save',
                    data: JSON.stringify({
                        country: {
                            CountryId: _countryId,
                            Name: _countryName
                        }
                    }),
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        if (data == "Success") {
                            console.log("Saved!");
                        } else {
                            elem.attr("data-input-mode", "edit");
                            elem.removeAttr("readonly");

                            console.log("Error occurs on the Database level!");
                        }
                    },
                    error: function () {
                        console.log("An error has occured!!!");
                    }
                });
            }
        });
    }
    });
});

0 个答案:

没有答案