10

I am looking for a way to validate two fields on ASP View page. I am aware that usual way of validating form fields is to have some @model ViewModel object included on a page, where the properties of this model object would be annotated with proper annotations needed for validation. For example, annotations can be like this:

[Required(ErrorMessage = "Please add the message")]
[Display(Name = "Message")]

But, in my case, there is no model included on a page, and controller action that is being called from the form receives plane strings as method arguments. This is form code:

@using (Html.BeginForm("InsertRssFeed", "Rss", FormMethod.Post, new { @id = "insertForm", @name = "insertForm" }))
{
<!-- inside this div goes entire form for adding rssFeed, or for editing it -->
    ...
            <div class="form-group">
                <label class="col-sm-2 control-label"> Name:</label>
                <div class="col-sm-10">
                    <div class="controls">
                        @Html.Editor("Name", new { htmlAttributes = new { @class = "form-control", @id = "add_rssFeed_name" } })
                    </div>
                </div>
            </div>

                <div class="form-group">
                    <label class="col-sm-2 control-label"> URL:</label>
                    <div class="col-sm-10">
                        <div class="controls">
                            @Html.Editor("Url", new { htmlAttributes = new { @class = "form-control", @id = "add_rssFeed_Url" } })
                        </div>
                    </div>
                </div>

            </div>
        </div>
            <!-- ok and cancel buttons. they use two css classes.  button-styleCancel is grey button and button-styleOK is normal orange button -->
        <div class="modal-footer">
            <button type="button" class="button-styleCancel" data-dismiss="modal">Close</button>
            <button type="submit" class="button-styleOK" id="submitRssFeed">Save RSS Feed</button>
        </div>
}

You can see that form is sending two text fields (Name and Url) to the RssController action method, that accepts these two string parameters:

[HttpPost]
public ActionResult InsertRssFeed(string Name, string Url)
{

    if (!String.IsNullOrEmpty(Name.Trim()) & !String.IsNullOrEmpty(Url.Trim()))
    {
        var rssFeed = new RssFeed();
        rssFeed.Name = Name;
        rssFeed.Url = Url;

        using (AuthenticationManager authenticationManager = new AuthenticationManager(User))
        {
            string userSid = authenticationManager.GetUserClaim(SystemClaims.ClaimTypes.PrimarySid);
            string userUPN = authenticationManager.GetUserClaim(SystemClaims.ClaimTypes.Upn);

            rssFeedService.CreateRssFeed(rssFeed);
        }
    }

    return RedirectToAction("ReadAllRssFeeds", "Rss");
}

If the page would have model, validation would be done with @Html.ValidationSummary method, but as I said I am not using modelview object on a page. Is there a way to achieve this kind of validation without using ModelView object, and how to do that? Thanks.

1
  • 1
    You only really lose unobtrusive validation by not using a model. You can still use the main validate library: jqueryvalidation.org/validate Commented Sep 15, 2014 at 8:16

1 Answer 1

10

If you are looking for server side validation you can use something like below using

ModelState.AddModelError("", "Name and Url are required fields.");

but you need to add

@Html.ValidationSummary(false)

to your razor view inside the Html.BeginForm section, then code will looks like below.

[HttpPost]
public ActionResult InsertRssFeed(string Name, string Url)
{

    if (String.IsNullOrEmpty(Name.Trim()) || String.IsNullOrEmpty(Url.Trim()))
    {
        ModelState.AddModelError("", "Name and URL are required fields.");
        return View();
    }

    var rssFeed = new RssFeed();
        rssFeed.Name = Name;
        rssFeed.Url = Url;

    using (AuthenticationManager authenticationManager = new AuthenticationManager(User))
    {
        string userSid = authenticationManager.GetUserClaim(SystemClaims.ClaimTypes.PrimarySid);
        string userUPN = authenticationManager.GetUserClaim(SystemClaims.ClaimTypes.Upn);

        rssFeedService.CreateRssFeed(rssFeed);
    }

    return RedirectToAction("ReadAllRssFeeds", "Rss");
}

If you are looking for only client side validation, then you have to use client side validation library like Jquery.

http://runnable.com/UZJ24Io3XEw2AABU/how-to-validate-forms-in-jquery-for-validation

Edited section for comment

your razor should be like this.

@using (Html.BeginForm("InsertRssFeed", "Rss", FormMethod.Post, new { @id = "insertForm", @name = "insertForm" }))
{
    @Html.ValidationSummary(false)

        <div class="form-group">
            <label class="col-sm-2 control-label"> Name:</label>
            <div class="col-sm-10">
                <div class="controls">
                    @Html.Editor("Name", new { htmlAttributes = new { @class = "form-control", @id = "add_rssFeed_name" } })
                </div>
            </div>
        </div>

            <div class="form-group">
                <label class="col-sm-2 control-label"> URL:</label>
                <div class="col-sm-10">
                    <div class="controls">
                        @Html.Editor("Url", new { htmlAttributes = new { @class = "form-control", @id = "add_rssFeed_Url" } })
                    </div>
                </div>
            </div>

        </div>
    </div>
        <!-- ok and cancel buttons. they use two css classes.  button-styleCancel is grey button and button-styleOK is normal orange button -->
    <div class="modal-footer">
        <button type="button" class="button-styleCancel" data-dismiss="modal">Close</button>
        <button type="submit" class="button-styleOK" id="submitRssFeed">Save RSS Feed</button>
    </div>
}

Hope this helps.

Sign up to request clarification or add additional context in comments.

6 Comments

thanks for answer. Exactly, I am trying to achieve server side validation. On client side I have validation with jquery.Anyway, if I turn off that ckient side, jquery validation, and put this code you provided, its still not working as it should. I am not getting message if I leave some of the fields empty.
Have you added @Html.ValidationSummary(false) to your razor view? Actually I have tested this and works fine for me.
Yes, I have added @Html.ValidationSummary(false) to razor view, right below <div class="form-group"> of @Html.Editor("Url"...) part.
I have added code which I suppose you are using in razor. Are you correctly referencing required scripts? can you check the whats render when you trying to validate putting debug points on action and check are you correctly return to the view with model error on it.
You can also use ModelState.AddModelError("Name", "Name is required");, and use the usual @Html.ValidationMessage("Name") in the view, instead of a validation summary.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.