수색…


소개

CRUD 연산은 데이터와 관련된 고전적인 (생성, 읽기, 업데이트, 삭제) 연산을 의미합니다.

ASP MVC 컨텍스트에는 Models와 그 이후의 뷰인 Controllers를 사용하여 데이터를 CRUD하는 여러 가지 방법이 있습니다.

한 가지 간단한 방법은 Visual Studio 템플릿에서 제공하는 스캐 폴딩 기능을 사용하고 필요에 맞게 사용자 정의하는 것입니다.

CRUD는 매우 광범위하게 정의되어 있으며 요구 사항에 맞는 다양한 변형이 있음을 명심하십시오. 예를 들어 Database first, Entity first 등.

비고

간단하게하기 위해이 CRUD 연산은 컨트롤러에서 엔티티 프레임 워크 컨텍스트를 사용합니다. 좋은 방법은 아니지만이 주제의 범위를 벗어납니다. 당신이 그것에 대해 더 알고 싶다면 엔티티 프레임 워크를 클릭하십시오.

만들기 - 컨트롤러 부분

작성 기능을 구현하려면 GETPOST의 두 가지 조치가 필요 합니다 .

  1. HTML 요소를 사용하여 사용자가 데이터를 입력 할 수있는 형식을 표시하는보기를 반환하는 데 사용되는 GET 동작입니다. 사용자가 데이터를 추가하기 전에 삽입 할 일부 기본값이있는 경우,이 조치의보기 모델 특성에 지정해야합니다.

  2. 사용자가 양식을 채우고 "저장"버튼을 클릭하면 양식의 데이터를 처리하게됩니다. 이제는 POST 작업이 필요합니다. 이 방법은 데이터를 관리하고 데이터베이스에 저장하는 작업을 담당합니다. 오류가있는 경우 저장된 양식 데이터 및 오류 메시지와 함께 리턴 된 동일한보기는 제출 조치 후에 어떤 문제점이 발생하는지 설명합니다.

이 두 단계는 컨트롤러 클래스의 두 Create () 메소드 내에 구현됩니다.

    // GET: Student/Create 
    // When the user access this the link ~/Student/Create a get request is made to controller Student and action Create, as the page just need to build a blank form, any information is needed to be passed to view builder
    public ActionResult Create()
    {
        // Creates a ViewResult object that renders a view to the response.
        // no parameters means: view = default in this case Create and model = null
        return View();
    }

    // POST: Student/Create        
    [HttpPost]
    // Used to protect from overposting attacks, see http://stackoverflow.com/documentation/asp.net-mvc/1997/html-antiforgerytoke for details
    [ValidateAntiForgeryToken]
    // This is the post request with forms data that will be bind the action, if in the data post request have enough information to build a Student instance that will be bind
    public ActionResult Create(Student student)
    {
        try
        {
        //Gets a value that indicates whether this instance received from the view is valid.
            if (ModelState.IsValid)
            {
                // Adds to the context
                db.Students.Add(student);
                // Persist the data 
                db.SaveChanges();
                // Returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action, in this case the index action.
                return RedirectToAction("Index");
            }
        }
        catch 
        {
            // Log the error (uncomment dex variable name and add a line here to write a log).
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
        }
        // view = default in this case Create and model = student
        return View(student);
    }

만들기 -보기 부분

@model ContosoUniversity.Models.Student

//The Html.BeginForm helper Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by an action method.                 
@using (Html.BeginForm()) 
{
    //Generates a hidden form field (anti-forgery token) that is validated when the form is submitted.
    @Html.AntiForgeryToken()
    
<div class="form-horizontal">
    <h4>Student</h4>
    <hr />

    //Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        //Returns an HTML label element and the property name of the property that is represented by the specified expression.            
        @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })

        <div class="col-md-10">
            //Returns an HTML input element for each property in the object that is represented by the Expression expression.
            @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })

            //Returns the HTML markup for a validation-error message for each data field that is represented by the specified expression.
            @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.FirstMidName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.FirstMidName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.FirstMidName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.EnrollmentDate, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.EnrollmentDate, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.EnrollmentDate, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
    //Returns an anchor element (a element) the text is Back to List and action is Index
    @Html.ActionLink("Back to List", "Index")
</div>

세부 정보 - 컨트롤러 부분

ur ~/Student/Details/5 :( ~ : 사이트 루트, Student : Controller, Details : Action, 5 : 학생 ID), 해당 ID로 학생을 검색 할 수 있습니다.

// GET: Student/Details/5
    public ActionResult Details(int? id)
    {
        // it good practice to consider that things could go wrong so,it is wise to have a validation in the controller
        if (id == null)
        {
            // return a bad request
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Student student = db.Students.Find(id);
        if (student == null)
        {
            // if doesn't found return 404
            return HttpNotFound();
        }
        return View(student);
    }

세부 정보 - 부분보기

// Model is the class that contains the student data send by the controller and will be rendered in the view
@model ContosoUniversity.Models.Student   

<h2>Details</h2>

<div>
   <h4>Student</h4>
<hr />
<dl class="dl-horizontal">
    <dt>
        //Gets the display name for the model.
        @Html.DisplayNameFor(model => model.LastName)
    </dt>

    <dd>
        //Returns HTML markup for each property in the object that is represented by the Expression expression.
        @Html.DisplayFor(model => model.LastName)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.FirstMidName)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.FirstMidName)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.EnrollmentDate)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.EnrollmentDate)
    </dd>
    <dt>
        @Html.DisplayNameFor(model => model.Enrollments)
    </dt>
    <dd>
        <table class="table">
            <tr>
                <th>Course Title</th>
                <th>Grade</th>
            </tr>
            @foreach (var item in Model.Enrollments)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Course.Title)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Grade)
                    </td>
                </tr>
            }
        </table>
    </dd>
</dl>
</div>
<p>
    //Returns an anchor element (a element) the text is Edit, action is Edit and the route value is the model ID property.
    @Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |
    @Html.ActionLink("Back to List", "Index")
</p>

편집 - 컨트롤러 부분

 // GET: Student/Edit/5
 // It is receives a get http request for the controller Student and Action Edit with the id of 5
    public ActionResult Edit(int? id)
    {
         // it good practice to consider that things could go wrong so,it is wise to have a validation in the controller
        if (id == null)
        {
            // returns a bad request
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        
        // It finds the Student to be edited.
        Student student = db.Students.Find(id);
        if (student == null)
        {
            // if doesn't found returns 404
            return HttpNotFound();
        }
        // Returns the Student data to fill out the edit form values.
        return View(student);
    }

이 메소드는 세부 액션 메소드와 매우 유사하지만 리팩토링에 적합한 후보이지만이 주제의 범위를 벗어납니다.

    // POST: Student/Edit/5
    [HttpPost]

    //used to To protect from overposting attacks more details see http://stackoverflow.com/documentation/asp.net-mvc/1997/html-antiforgerytoke
    [ValidateAntiForgeryToken]

    //Represents an attribute that is used for the name of an action.
    [ActionName("Edit")]
    public ActionResult Edit(Student student)
    {
        try
        {
            //Gets a value that indicates whether this instance received from the view is valid.
            if (ModelState.IsValid)
            {
                // Two thing happens here:
                // 1) db.Entry(student) -> Gets a DbEntityEntry object for the student entity providing access to information about it and the ability to perform actions on the entity.
                // 2) Set the student state to modified, that means that the student entity is being tracked by the context and exists in the database, and some or all of its property values have been modified.
                db.Entry(student).State = EntityState.Modified;

                // Now just save the changes that all the changes made in the form will be persisted.
                db.SaveChanges();

                // Returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action, in this case the index action.
                return RedirectToAction("Index");
            }
        }
        catch
        {
            //Log the error add a line here to write a log.
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
        }

        // return the invalid student instance to be corrected.
        return View(student);
    }

삭제 - 컨트롤러 부분

get 요청에서 삭제 작업을 수행하려는 유혹에 저항하는 좋은 습관입니다. 엄청난 보안 오류 일 것이고, 항상 post 메소드에서 수행되어야합니다.

    // GET: Student/Delete/5
    public ActionResult Delete(int? id)
    {
        // it good practice to consider that things could go wrong so,it is wise to have a validation in the controller
        if (id == null)
        {
            // returns a bad request
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        // It finds the Student to be deleted.
        Student student = db.Students.Find(id);
        if (student == null)
        {
            // if doesn't found returns 404
            return HttpNotFound();
        }
        // Returns the Student data to show the details of what will be deleted.
        return View(student);
    }

    // POST: Student/Delete/5
    [HttpPost]

    //Represents an attribute that is used for the name of an action.
    [ActionName("Delete")]

    //used to To protect from overposting attacks more details see http://stackoverflow.com/documentation/asp.net-mvc/1997/html-antiforgerytoke
    [ValidateAntiForgeryToken]
    public ActionResult Delete(int id)
    {
        try
        {
            // Finds the student
            Student student = db.Students.Find(id);

            // Try to remove it
            db.Students.Remove(student);

            // Save the changes
            db.SaveChanges();
        }
        catch
        {
            //Log the error add a line here to write a log.
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
        }

        // Returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action, in this case the index action.
        return RedirectToAction("Index");
    }


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow