user3163213
user3163213

Reputation: 701

working with bool in mvc action

I am trying to validate a string in MVC.

Scenario -

I have a Table and checking a string whether it is available in this table or not and according to that Validation is happening.

While saving a string in this table, this string is being validated by another function CheckTagName().

If result is true then I want to save it further.

   public void SaveTag(string tagname) {
            CheckTagName(tagname);
            if(!String.CheckTagName(string tagname))
            {
            TagTable tag = new TagTable();
            tag.TagName = tagname;
            db.TagTables.InsertOnSubmit(tag);
            db.SubmitChanges();
    }



        }

Function for string validation-

  public ActionResult CheckTagName(string tagname) {
            var tagtable = (from u in db.TagTables
                            where u.TagName.Contains(tagname)
                            select u);
            if (tagtable != null) {
                return Json(new { success = false });
            }
            else {
                return Json(true);
            }
        }

I am a newbie to this validation thing. Please assist me how do validate in MVC on bool basis result.

Upvotes: 0

Views: 54

Answers (2)

ramiramilu
ramiramilu

Reputation: 17182

First make a function to check existence of tagname, which can be as follows -

 public bool CheckTagName(string tagname) {
            var tagtable = (from u in db.TagTables
                            where u.TagName.Contains(tagname)
                            select u).FirstOrDefault();
            if (tagtable != null) {
                return true;
            }
            else {
                return false;
            }
        }

Then consume above validation function in any other method as shown below -

  public void SaveTag(string tagname) 
  {
        if(!CheckTagName(tagname))
        {
            TagTable tag = new TagTable();
            tag.TagName = tagname;
            db.TagTables.InsertOnSubmit(tag);
            db.SubmitChanges();
        }
  }

PS - Code in my answer is not tested. I incorporated code to give you an idea.

Upvotes: 2

Igor
Igor

Reputation: 15893

public void SaveTag(string tagname) 
{
    if(!CheckTagName(tagname))
    {
        TagTable tag = new TagTable();
        tag.TagName = tagname;
        db.TagTables.InsertOnSubmit(tag);
        db.SubmitChanges();
    }
}

public bool CheckTagName(string tagname) 
{
    var tagtable = (from u in db.TagTables
                    where u.TagName.Contains(tagname)
                    select u);
    return tagtable == null;
}

Upvotes: 1

Related Questions