T
T
Tsiren Naimanov2016-11-11 14:50:26
ASP.NET
Tsiren Naimanov, 2016-11-11 14:50:26

What responses are best given from the server?

For example

[HttpPost]
        public ActionResult Create(ViewModel vm)
        {
            if (ModelState.IsValid)
            {
                var model = Mapper.Map<ViewModel, Post>(vm);
                ps.CreatePost(model);
                ps.SavePost();
                RedirectToRoute("Slug", new { controller = "Log", action = "Details", id = model.Id, slug = model.Slug });
            }
            return View(vm);
        }

Almost everything is clear here ...
But here
public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Post model = ps.GetPostById(id.Value);
            if (model == null)
            {
                return HttpNotFound();
            }
            var vm = Mapper.Map<Post, PostViewModel>(model);
            return View(vm);
        }

Is it correct, with an empty identifier, we get a bad request, but if the model is not found, 404?
Is there any template? best practice?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew, 2016-11-11
@ImmortalCAT

Everything is correct. If you think about the meaning of the method, it should receive the id of the entry and return either its contents or the flag of its absence.
If you replace int?with intand remove the first check, the application will work exactly the same, but the error handling will be handled automatically by the framework. It will look for a method with a matching signature, fail to find one, and issue a standard error message.
Thus, the zero value idfor the logic is not important - this is done to more clearly show how errors can be handled manually.

S
Sergey, 2016-11-11
@senal

It is not correct to compare Create and Edit. To Edit questions do not arise IMHO correctly and clearly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question