html.validation asp.net razor - asp.net-mvc

How can I add a simple validation in my code? If value = 0 I don't want the controller to process the form. If anything else is selected except 0, I want the controller to process the form.
#using (Html.BeginForm("GenerateReport", "Admin", FormMethod.Get))
{
<select id="reportId" name="reportId" class="form-control">
<option value="0">Select</option>
<option value="1">Religion</option>
<option value="2">Address</option>
<option value="3">Job</option>
<option value="4">Degree</option>
<option value="7">Age</option>
</select>
<input type="submit" value="Print" id="rlist_type" />
}

This article provides basic information on ASP.NET MVC 5 validation
http://www.asp.net/mvc/overview/getting-started/introduction/adding-validation
I would leave the value for the first option empty then add a [Required] attribute on the object that I was using to capture the form post.
public class AdminScreenFormPost
{
[Required]
public int reportId { get; set; }
}
Inside the controller add
if (!ModelState.IsValid)
{
return View();
}
In the razor view add this so it will displays the validation results
#Html.ValidationSummary(true)
I would also look into ModelState.AddModelError
ModelState.AddModelError("MyDropDownListKey", "Please Select");

Related

unable to save dropdown in asp.netcore using razor pages

let me know whats wrong here , i am unable to save after selecting from drop down and clicking on save
<label asp-for="application.number" class="control-label"></label>
<select class="form-control" name="Tower">
<option>Select Tower</option>
<option>numbers</option>
<option>1</option>
<option>2</option>
<option>3</option>
i think i am getting error in below models
#Html.DisplayFor(modelItem => item.Tower)
You can use below code to generate dropdown:
#Html.DropDownList("Tower",new SelectList(#ViewBag.TowerList, "TowerId","TowerName"),"Select Tower", new { #class= "form-control"})
i am unable to save after selecting from drop down and clicking on save
You can set value attribute for <option> elements. Besides, you can refer to the following example to modify your code.
<form method="post">
<label asp-for="application.number" class="control-label"></label>: #Model.application.number
<select class="form-control" name="Tower">
<option>Select Tower</option>
<option>numbers</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="submit" value="Save" />
</form>
In page model class
public class TestModel : PageModel
{
[BindProperty]
public int Tower { get; set; }
public MyClass application { get; set; }
public void OnGet()
{
application = new MyClass { number = 0 };
}
public IActionResult OnPost()
{
//code logic here to save the selected value
application = new MyClass { number = Tower };
return Page();
}
}
public class MyClass
{
public int number { get; set; }
}
Test Result

POSTing data in ASP.NET MVC 4

I'm currently working on an ASP.NET MVC 4 app. I'm pretty new to ASP.NET MVC. Right now, I have a form coded up like this:
<form role="form" method="post" action="/contact/new">
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label for="name">Name</label>
<div id="name">
<input class="form-control" type="text" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label for="gender">Gender</label>
<select id="gender" class="form-control">
<option value="m">Male</option>
<option value="f">Female</option>
</select>
</div>
<div class="form-group">
<label for="email">Email Address</label>
<input class="form-control" type="email" autocomplete="off" />
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
My controller and action look like the following:
public class ContactController : Controller
{
public ActionResult New()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult New()
{
return View();
}
}
My challenge is, I do not know what to put for the parameters of the HttpPost action in the controller. What should I put here?
Thanks!
MVC is based on Model View Controller. you should have a model for the View and your view should be strongly typed to its model.
If you don't want strongly typed view with some Model class, you have to read the form data from Request:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult New(FormCollection form)
{
string Name = form["UserName"].ToString();
return View();
}
and add name attribute to your input elements:
<input class="form-control" type="text" name="UserName" autocomplete="off" />
you should see these few links for making understanding of strongly type view and form post:
Dyanmic VS Strong Typed Views
What is strongly typed View in asp.net mvc
Why we need Strongly typed View
First, you need to ensure that the /name/ attributes on your form controls are filled out.
Then, you should define a ViewModel class called NewContactViewModel and your ActionResult as such:
public class NewContactViewModel
{
public string name { get; set; }
public string gender { get; set; }
public string email { get; set; }
}
[HttpPost]
public ActionResult New(NewContactViewModel model)
{
}

Set selected value of a dropdown in Razor view

I am trying to set the selected value in a dropdown in a razor view.
<select id="drpStatus" name="status">
<option value="A">Active</option>
<option value="S">Suspended</option>
<option value="T">Terminated</option>
<option value="D">Deleted</option>
</select>
//I am trying with the below code, based on the value in Model, I want to set the particular option as selected
<option selected=#{if(#Model!=null && #Model.Status=='A'){'selected'}} value="A">Active</option>
Above code is not working, please let me know if I am working in a right direction or is there any other/better way to achieve it.
Try this from your controller
Controller :
var record = db.Records.Find(id);
ViewBag.DropStatus = new SelectList(ListOfStatus, record.Status);
The first parameter for SelectList should be an IEnumerable which will serve as the data source for your DropDownList, the second parameter is for the selected value, so just pass the status property of the record you want to edit.
View:
#Html.DropDownList("Status", string.Empty)
The first parameter is the name of the ViewBag we assigned in the controller, it will also serve as the name when you post the data. Hope I've made myself clear.
The following is one of some possible solutions
#{
ViewBag.Title = "Index";
Func<char, MvcHtmlString> function = (c) => Model != null && Model.Status == c
? MvcHtmlString.Create("selected='selected'")
: MvcHtmlString.Empty;
}
<h2>Index</h2>
<select id="drpStatus" name="status">
<option #function('A') value="A">Active</option>
<option #function('S') value="S">Suspended</option>
<option #function('T') value="T">Terminated</option>
<option #function('D') value="D">Deleted</option>
</select>
It would be better to use SelectList in your ViewModel.
Another possible solution is using Razor's helper tag in the cshtml:
#helper SetGender(string dropdownvalue)
{
var selected = string.Format("value=\"{0}\"", dropdownvalue);
if ((string.IsNullOrEmpty(dropdownvalue) && string.IsNullOrEmpty(User.GetClaim(ClaimTypes.Gender.ToString()))) ||
(User.GetClaim(ClaimTypes.Gender.ToString()) == dropdownvalue))
{
selected = string.Concat("selected='selected' ", selected);
}
#Html.Raw(selected);
}
<select name="gender">
<option #SetGender("") >-not set-</option>
<option #SetGender("male") >male</option>
<option #SetGender("female") >female</option>
</select>
#{
List<SelectListItem> lstOrderTypes = new List<SelectListItem>();
lstOrderTypes.Add(new SelectListItem {Value = "1", Text = "plan1" });
lstOrderTypes.Add(new SelectListItem {Value = "2", Text = "plan2" });
}
#functions {
public static string GetString(IHtmlContent content)
{
var writer = new System.IO.StringWriter();
content.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
}
#{
var x = GetString(Html.DisplayFor(model => model.OrderType));
}
<select>
#foreach (SelectListItem option in lstOrderTypes)
{
<option value="#option.Value" selected="#(option.Value == x)">#option.Text</option>
}
</select>

Populating a select box on my razor view

I have the following class:
public class Note : TableServiceEntity
{
public string Description { get; set; }
public string NoteDetailsJSON { get; set; }
}
It contains short descriptions that I would like to put into a select list in my view.
I get the data from the table like this.
Notes = noteTable.GetAll()
I have my viewmodel look like this:
public IEnumerable<Note> Notes { get; set; }
However when I try to populate my select box I get only the following:
#Html.DropDownListFor(
x => x.Level,
new SelectList(Model.Notes, "Description", "Description"),
new { style = "display: inline;" }
)
<select id="Level" name="Level" style="display: inline;"><option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
Some help on how to populate the select box would be much appreciated.
I don't get what your question or problem is. Most probably noteTable.GetAll() simply returns empty objects.
So assuming you have the following view model which contains a list of notes:
public class MyViewModel
{
public string Level { get; set; }
public IEnumerable<Note> Notes { get; set; }
}
and your controller action properly populates this model:
public ActionResult Index()
{
var model = new MyViewModel
{
Notes = noteTable.GetAll().ToList() // make sure that this returns some data
};
return View(model);
}
obviously the best way to ensure that your problem is not in the data source is to initially hardcode some data:
public ActionResult Index()
{
var model = new MyViewModel
{
Notes = Enumerable.Range(1, 5).Select(x => new Note
{
Description = "note description " + x
})
};
return View(model);
}
in your view you should be able to display the dropdownlist:
#model MyViewModel
#Html.DropDownListFor(
x => x.Level,
new SelectList(Model.Notes, "Description", "Description"),
new { style = "display: inline;" }
)

what is the best routing url strategy for supporting multi field filtering in asp.net mvc

i have an asp.net mvc page where i show a dataset in a report. I have a filter section at the top and each filter changes the dataset from:
Controller/Action
to something like this:
Controller/Action/Field1Filter
If there is no filter selected, i put a zero in this part of the url. I keep adding more fields to filter by and now i end up with this type of URL.
Controller/Action/Field1Filter/Field2Filter/Field3Filter/Field4Filter/Field5Filter/Field6Filter . . . .
so i end up with URLs like this:
Controller/Action/0/0/1/0/5/0
Is there anyway to do this as:
I am going to be adding some more fields to filter by
I want to support multiselect for some of these fields so i dont see how i can support this in the current model
Example from my application:
[HttpGet]
public ActionResult TaskSearch(TaskSearchCriteria criteria)
{
//Do something with criteria
}
public class TaskSearchCriteria
{
public List<int> Statuses { get; set; } //List of ids
public DateTime? CreationDateFrom { get; set; }
public DateTime? CreationDateTo { get; set; }
public bool SearchInTitle { get; set; }
}
Part of form:
<form method="GET" action="/Task/TaskSearch" name="searchform">
<select id="Search_Statuses" multiple="multiple" name="Statuses">
<option value="-1">*All</option>
<option value="-8">*Opened</option>
<option value="-4">*Active</option>
<option value="-3">*Closing</option>
<option value="-2">*Beginning</option>
<option value="21">Closed</option>
<option value="19">Created</option>
<option value="20">In progress</option>
<option value="22">Requires testing</option>
</select>
Example query string:
SearchInTitle=true&SearchInTitle=false&Statuses=19&Statuses=20&Statuses=22&CreationDateFrom=2010.07.01
If you pass one field many times, it will be translated to Array.

Resources