Przemysław Szkaradek Ответов: 0

Как добавить проверку в MVC - jquery ajax json


The code below works and using modal windows I can add edit and delete records without the need to refresh the pages.

I tried to add validation but it does not work. How can I add validation to the following code? I am asking for help regarding validation.


Что я уже пробовал:

//View Model
public class PositionsViewModel
    {
        public IEnumerable<Positions> ListPositions { get; set; }
        public int IdPositions { get; set; }  
        [MaxLength(50, ErrorMessage = "Name max 50 znaków")]
        [Display(Name = "Positions")]
        [Required(ErrorMessage = "Required position")]
        public string NamePosition { get; set; }
        [Display(Name = "Active")]
        [Required(ErrorMessage = "Zaznacz pole")]
        public bool "Active")]{ get; set; }
    }


Я отправляю данные с помощью Json

public ActionResult ListPosition()
        {
            var listPosition= db.Position.ToList();
            var viewModel = new PositionViewModel()
            {
                ListPosition = listPosition= 
            };
            return View(viewModel);
        } 
public JsonResult EditPosition( int? idRecord)
            {
                Position position = db.Position.Find(idRecord);
                string value = string.Empty;
                value = JsonConvert.SerializeObject(position, Formatting.Indented, new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });
                return Json(value, JsonRequestBehavior.AllowGet);
            }


        [HttpPost]
        public JsonResult SaveAndEditPosition(int IdPosition, string NamePosition, bool Active)
        {
            var result = false;
            if (ModelState.IsValid)
            {
                //New Position
                Position position = new Position();
                position.IdPosition = IdPosition;
                position.NamePosition,  = NamePosition, ;
                position.Active = Active;

                if (position .IdPosition == 0)
                {
                    db.Position.Add((position );
                    result = true;
                }
                else
                {
                    //Edit position
                    db.Entry(position).State = EntityState.Modified;
                    result = true;
                }
                db.SaveChanges();
            }


                result = false;

            return Json(result, JsonRequestBehavior.AllowGet);
        }

//View
@model AplikacjaHelpDesk.ViewModels.StanowiskaViewModel
 <div class="col-sm-5">
        
            <tr class="panel panel-primary" text-transform uppercase; text-combine-upright:all; opacity 0.6;">
                            @foreach (var item in Model.ListPositions )
            {
                                    @Html.HiddenFor(modelItem => item.IdPosition, new { @id = "PositionId" })

                                }
        <table align="left" class=" table panel panel-primary panel-title table-responsive"><tbody><tr><th>                    @Html.DisplayNameFor(model => model.NamePosition)
                </th>                <th style="width: 100px">                    @Html.DisplayNameFor(model => model.Active)
                </th>                <th></th>            </tr><tr><td>                        @Html.DisplayFor(model => item.NamePosition)
                    </td>                    <td>                        @Html.DisplayFor(model => item.Active)
                    </td>                    <td style="width: 220px">                        <span class="btn btn-primary glyphicon glyphicon-pencil ">
                            <a href=" #" style="color: white">Edit</a>
                        </span>
                    </td>                </tr></tbody></table>
    </div>

 <div class="modal fade" id="MyModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <a href="#" class="close">×</a>
                    <h4 id="ModalTitle"></h4>
                </div>
                <div class="modal-body">
                                                                    
                               

                                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                                @Html.HiddenFor(m => m.IdPosition, new { @id = "PositionId" })
                                <div class="form-group">
                                    @Html.DisplayNameFor(model => model.NamePosition)<br> 
                                    @Html.TextBoxFor(m => m.NazwaStanowiska, new { @id = "NamePosition", @class = "form-control", @placeholder = "Name Position" })
                                    @Html.ValidationMessageFor(m => m.NamePosition, "")
                                </div>
                                <div class="form-group">
                                    @Html.DisplayNameFor(model => model.Active)<br>
                                    @Html.CheckBoxFor(m => m.CzyAktywny, new { @id = "PositionActive" })
                                    @Html.ValidationMessageFor(m => m.Active, "")
                                </div>
                                <div class="col-md-2">
                                    <a href="#" class="btn btn-block btn-danger">Save  </a>
                                </div>
                                                    
                    
                </div>
            </div>
        </div>
    </div>




function AddNewPosition(IdPosition) {
        $("#form")[0].reset();
        $("#PositionId").val(0);
        $("#ModalTitle").html("Add new position");
        $("#MyModal").modal();

    }

 var SaveRecordToDataBase = function () {
        var data = $("#SubmitForm").serialize();

        if (!$("#SubmitForm").valid())
        {
            return false;
        }
        $.ajax({
            type: "POST",
            url: "SaveAndEditPosition",
            data: data,
            success: function (result) {
                $("#MyModal").modal("hide");
                $("#confirmSave").modal("show");
                setTimeout(function () { window.location.href = "/Position/ListPosition" }, 2000);
            }
        })
    }


 function EditRecordPosition(IdPosition) {
        var url = "/Position/EditPosition?idRecord=" + IdPosition;
        $("#ModalTitle").html("Uaktualnij stanowisko");
        $("#MyModal").modal();
        $.ajax({
            type: "GET",
            url: url,
            success: function (data) {
                var obj = JSON.parse(data);
                $("#PositionId").val(obj.IdPosition);
                $("#NamePosition").val(obj.NamePosition);
                $("#PositionActive").val(obj.Active);
            }
        })

    }


//How can I validate fields in the form?

0 Ответов