Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP .NET MVC Form fields Validation (without model)

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.

like image 214
Vladimir Avatar asked Sep 15 '14 08:09

Vladimir


People also ask

Which of the following are alternatives to perform model validation instead of using built-in validation attributes?

Alternatives to built-in attributes If you need validation not provided by built-in attributes, you can: Create custom attributes. Implement IValidatableObject.

How can we make field required in MVC?

From the model class drop down, select "Employee" as the model. Click on the "Add" button. It will automatically create the view from the model. Add the "[Required]" attribute to the field that you want to make mandatory for insertion.

Can we do validation in MVC using data annotations?

In ASP.NET MVC, Data Annotation is used for data validation for developing web-based applications. We can quickly apply validation with the help of data annotation attribute classes over model classes.


1 Answers

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.

like image 170
DSR Avatar answered Nov 15 '22 19:11

DSR