0

Razor:

@Html.TextBoxFor(kod => kod.Name)
@Html.ValidationMessage("Name","Client Error Message")

Controller:

[HttpPost]
    public JsonResult JsonAddCustomer(Customers customer, string returnUrl)
    {
        if (customer.Name.Trim().Length == 0)
        {
            ModelState.AddModelError("Name", "Server Error Message");
        }

        //Eğer hata yoksa veri tabanına kayıt yapılıyor.
        if (ModelState.IsValid)
        {
            try
            {
                CusOpp.InsertCustomer(customer);
                return Json(new { success = true, redirect = returnUrl });
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", "Error");
            }
        }

        return Json(new { errors = GetErrorsFromModelState() });
    }

I want to write validation error message. I did this like above, but @Html.ValidationMessage("Name","Client Error Message") does not work. In fact, I was already expecting it.

I want to show like this statement's result: @Html.ValidationMessageFor(m => m.name) ,but I cant use this, because I used entity-data-model.

Should I add [Required] statement to data-model classes or any way that I do this. Sorry for bad explanation.

Thanks.

AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197

2 Answers2

2

You should return PartialViews instead of JSON in this case. Only in the case of success you could return JSON:

[HttpPost]
public ActionResult JsonAddCustomer(Customers customer, string returnUrl)
{
    // Warning: the following line is something horrible => 
    // please decorate your view model with data annotations or use
    // FluentValidation.NET to validate it. 
    // Never write such code in a controller action.
    if (customer.Name.Trim().Length == 0)
    {
        ModelState.AddModelError("Name", "Server Error Message");
    }

    //Eğer hata yoksa veri tabanına kayıt yapılıyor.
    if (ModelState.IsValid)
    {
        try
        {
            CusOpp.InsertCustomer(customer);
            return Json(new { success = true, redirect = returnUrl });
        }
        catch (Exception e)
        {
            ModelState.AddModelError("", "Error");
        }
    }

    return PartialView(customer);
}

Now inside the success callback of your AJAX request you can test whether the POST action succeeded or not:

success: function(result) {
    if (result.redirect) {
        // we are in the success case => redirect
        window.location.href = result.redirect; 
    } else {
        // a partial view with the errors was returned => we must refresh the DOM
        $('#some_container').html(result);

        // TODO: if you are using unobtrusive client side validation here's 
        // the place to call the $.validator.unobtrusive.parse("form"); method in order 
        // to register the unobtrusive validators on the newly added contents
    }
}

Here's a similar post that you might also read through.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • There are a lof of column to validate in my model. So I dont want to write "if statements" for validation. I there any solution like public class FeedBack { [Required] [Display(Name = "Feedback")] public string Feedback { get; set; } } – AliRıza Adıyahşi Jun 29 '12 at 12:13
  • Yes, exactly, you should use Data Annotations on your view model and decorate the corresponding properties with the necessary attributes instead of writing those if conditions inside your controller action. – Darin Dimitrov Jun 29 '12 at 12:14
  • I use entity-model. How I can do this? – AliRıza Adıyahşi Jun 29 '12 at 12:15
  • Oh, no, that's a very wrong approach. You should never pass domain entities to views. You should work with view models which are classes that you specifically design for the requirements of your views. – Darin Dimitrov Jun 29 '12 at 12:15
  • On which note, I started to use AutoMapper recently for converting between my data models and my view models. I thought it worth mentioning for the OP should they be wondering about conversions. – Jamie Dixon Jun 29 '12 at 12:30
  • @JamieDixon, thanks. That's an excellent remark about AutoMapper. I use it all the time in all projects. – Darin Dimitrov Jun 29 '12 at 12:32
0

Your Idea with the Required annotation on the model is a good approach. You can set a Error Message on the Required annotation.

[Required(ErrorMessage = "Please enter a name")]

and remove your if in your action..this:

if (customer.Name.Trim().Length == 0)
        {
            ModelState.AddModelError("Name", "Server Error Message");
        }

the ModelState.IsValid will do the job for you on the client and server side.

And use your @Html.ValidationMessageFor(m => m.name) in your view

theforce
  • 1,505
  • 1
  • 11
  • 13