ASP .NET MVC Form fields Validation (without model)

19,903

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.

Share:
19,903
Vladimir
Author by

Vladimir

Currently working with C#, ASP.NET Technologies, Windows Azure, MVC, Entity Framework, MS SQL, WCF, WEB API, PowerShell, HTML, Bootstrap, JQuery, Ajax. Also worked with Java, JEE, JSP, Servlets, XML, JavaScript, Web Services (Apache CXF), MySQL. I have also worked with following languages, tools and technologies: C++, C, Pascal, Python, MSSQL, Google App Engine, Apache Tomcat/TomEE, Eclipse IDE, Power Designer ...

Updated on July 25, 2022

Comments

  • Vladimir
    Vladimir almost 2 years

    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.