Ok here is my challenge:
I want to create a dropdownlist with three strings in my Register View - "Please Select", "I am a client", and "I am a vendor". When the user selects the "I am a client" and submits he is added to the "Client" role. When the user selects the "I am a Vendor" role he is added to the "Vendor" role. If the user doesn't select either and leaves on "Please select" validation occurs.
I can get the roles to directly populate via the ViewBag. Here's how:
Register.cshtml -
<div class="editor-label">
#Html.LabelFor(m => m.Role, "I am a:")
</div>
<div class="editor-field">
#Html.DropDownList("Role", ViewBag.Roles as SelectList,"Please Select")
</div>
AccountModel.cs -
public class RegisterModel
{
[Required]
[Display(Name = "Role")]
public string Role { get; set; }
AccountController.cs -
public ActionResult Register()
{
ViewBag.Roles = new SelectList(Roles.GetAllRoles().ToList());
return View();
What I still need to accomplish -
Currently the dropdownlist only populates the actual roles. This is not what I want though.
How do I instead create a dropdownlist for three strings in my Register View - "Please Select", "I am a client", and "I am a vendor".
I have no hair left on this one and will be grateful to anyone who can help me to figure this one out. Thanks.
Something similar to below would work perfectly:
public class RegisterModel
{
[Required]
[Display(Name = "Role")]
public string Role { get; set; }
Then you can have something similar to this in your view.
#Html.DropDownListFor(x => x.Role, new[] {
new SelectListItem() {Text = "I am a vendor", Value = "Vendor"},
new SelectListItem() {Text = "I am a client", Value = "Client"}
}, "Pick a basket")
Edit: String is a reference type and is nullable by default.
You can set the list values in the constructor: SelectList(dataObjects, valueField, textField)
ViewBag.Roles = new SelectList(Roles.GetAllRoles().ToList(), "Id", "Name");
This allows you to define what attributes of your Role objects are being set as the values and texts of the options.
Related
I want to create Html helper method to add title html attribute for each items in DropDownListFor control.
#Html.DropDownListFor(m=> m.StateId, Model.States)
public class Model
{
public int? StateId {get; set;}
public List<SelectListItem> States {get; set;}
}
In controller,
Model m = new Model();
m.States = GetStates(). This will return List<SelectListItem> of States with Value and Text.
Now I want to create html helper method to add title attribute for each item with text value.
You will need to create on your own.
You can pull from similar implementation
Adding html class tag under <option> in Html.DropDownList
Also
give a try to
#Html.DropDownListFor(model => model.priority, new SelectList(ViewBag.Priority, "Value", "Text"), "-- Select Priority --", new { #class = "required", title="priority" })
i am very much new to MVC3 and working with MVC3 razor application. I need to validate a textbox on View in such a way that, the textbox will accept only those strings which are starting with characters "PR" and 4th character of that string must be "2". It would be great if anybody helps me. Thanks in advance
Well you need regex. I'm not exactly sure what the regex would be and what your string contains. But if you need to have 2 matches in there, you could split it and use 2 textboxes and join the values on post.
ViewModel:
public class MyViewModel
{
[RegularExpression("^PR[A-Za-z0-9]", ErrorMessage= "Invalid Text1")]
public string MyText1 { get; set; }
[RegularExpression("^2[A-Za-z0-9]", ErrorMessage= "Invalid Text2")]
public string MyText2 { get; set; }
}
Warning, this regex may be faulty. I invite others to edit/post comments and i can update it with correct regex
View:
#model MyProject.Models.MyViewModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.MyText1)
#Html.TextBoxFor(m => m.MyText2)
<button type="submit">Submit</button>
}
Hope this helps
Model
public class RegisterModel
{
public int ID { get; set; }
[RegularExpression(#"^PR[a-zA-Z0-9]2([a-zA-Z0-9]*)$", ErrorMessage = "Please enter valid Name.")]
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
}
View
#using (Html.BeginForm("DYmanicControllerPage", "Test", FormMethod.Post, new { id = "FrmIndex" }))
{
<div>
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name)
#Html.ValidationMessageFor(m => m.Name)
</div>
}
I am new to MVC. I am facing problem to get Date of birth value from view into controller by using view model. I am using view model for getting form values and getting all other textboxes values. But I always get null value for date.
My view model is like this.
public class Student
{
[Required(ErrorMessage = "Date of birth is required")]
[DataType(DataType.Date), DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:dd/MM/yy}",ConvertEmptyStringToNull=false)]
public DateTime? DateOfBirth { get; set; }
}
My controller which is called after form posting is:
[HttpPost]
public ActionResult StudentPersonalReg(Student stud)
{
DateTime? dateofbirth = stud.DateOfBirth;
return RedirectToAction("Registration");
}
My view is
#model eEducation.Models.UserModel.Student
#Html.TextBoxFor(x => x.DateOfBirth)
#Html.ValidationMessageFor(x => x.DateOfBirth)
Problem is that I always get null value for date in controller.
I have also tried setting DateTime.Now to the viewmodel when I am calling the view from controller.
I am not using strongly typed view.
Please help me in this regard.
I am passing my model to view by controller method
public ViewResult Registration()
{
var db = new eEducationEntities();
List<CountryMaster> queryCountry = db.CountryMasters.ToList();
List<StateMaster> queryState = db.StateMasters.ToList();
Student stds = new Student();
stds.Countries = queryCountry;
stds.States = queryState;
stds.DateOfBirth = DateTime.Now;
return View("~/Views/UserSection/StudentRegistration.cshtml", stds);
}
You need to be using a Html.BeginForm() on your view model. You can even specify the controller action it posts back to.
#model eEducation.Models.UserModel.Student
#using (Html.BeginForm("StudentPersonalReg", "ControllerName")) {
#Html.ValidationSummary(true)
#Html.TextBoxFor(x => x.DateOfBirth)
#Html.ValidationMessageFor(x => x.DateOfBirth)
<p>
<input type="submit" value="Submit" />
</p>
}
I have two model class in MVC3 one for Services which have those properties
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public int ChildOf { get; set; }
It also have a DB table by Entityframework
Another model is Quata which have those properties
public int ID { get; set; }
public string Sender_Name { get; set; }
public string Description { get; set; }
.....
......
public Services Service_ID { get; set; }
It also have a DB table by Entityframework
I want to create a Razor(C#) view (for Quata) where user can send a quata by fill a html form but where i wanna show a dropdown list with Services ID as dropdown value and Services Name as dropdown text which is also come dynamically from the Services DB table .
My question is how i should create that dynamic dropdown list by #Html.DropDownListFor ? and send the selected data from that dropdown list to a Controller ?
Try this
Controller:
public ActionResult Create()
{
var Services = new Services();
Services.Load(); //load services..
ViewBag.ID = new SelectList(Services.ToList(), "Id", "Name");
return View();
}
[HttpPost]
public ActionResult Create(Quata Quata)
{
//save the data
}
A strong Typed View: (Using Razor)
#model Quata
#using (Html.BeginForm()) {
<fieldset>
<legend>Quata</legend>
<div>
#Html.LabelFor(model => model.Service_ID.ID, "Service")
</div>
<div>
#Html.DropDownList("ID", String.Empty)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
take a look at #Html.DropDownListFor
So say your viewmodel has a list of said Services.
Something that may work for you is the following (you may not need a for loop here, editor is supposed to eliminate that, but I had some weird binding issues).
In your top level view which points at your viewmodel (#model Quata, assuming Quata is your viewmodel) have this code :
#For i = 0 To Model.DropdownListInput.Count - 1
Dim iterator = i
#Html.EditorFor(Function(x) x.DropdownListInput(iterator), "EnumInput")
Next
In your Editor Template (create a subfolder under the view folder this dropdownlist will be in called editor templates and name the template whatever you desire, mine was EnumInput).
In your editor template, which should point at your model for Services (#model Services) have something like the following code (with substitutions for your appropriate variable names):
#<div class="editor-label">
#Html.LabelFor(Function(v) v.value, Model.DisplayName)
</div>
#<div class="editor-field">
#Html.DropDownListFor(Function(v) v.value, New SelectList(Model.ParamEnums, "ValueForScript", "EnumValue"), "--Please Select A Value--")
#Html.ValidationMessageFor(Function(v) v.value)
</div>
Replace the list with your list and the lambda values with yours (#Html.DropDownListFor(x => x.id, New SelectList(x.ServiceList, "ID", "Name"), "--Please Select A Value--") or something like that.
Note that this code is in VB, but it should provide a rough guide.
Following is my model property
[Required(ErrorMessage = "Please Enter Short Desciption")]
[StringLength(200)]
public string ShortDescription { get; set; }
And following is my corresponding View code
#Html.TextAreaFor(model => model.Product.ShortDescription, new { cols = "50%", rows = "3" })
#Html.ValidationMessageFor(model => model.Product.ShortDescription)
And this is how it shows in the browser, the way i want.
Now, since there is a bug in Microsoft's MVC3 release, I am not able to validate and the form is submitted and produces the annoying error.
Please tell me the work around or any code that can be substituted in place of TextAreaFor. I can't use EditorFor, because with it, i can't use rows and cols parameter. I want to maintain my field look in the browser. Let me know what should be done in this case
In the controller action rendering this view make sure you have instantiated the dependent property (Product in your case) so that it is not null:
Non-working example:
public ActionResult Foo()
{
var model = new MyViewModel();
return View(model);
}
Working example:
public ActionResult Foo()
{
var model = new MyViewModel
{
Product = new ProductViewModel()
};
return View(model);
}
Another possibility (and the one I recommend) is to decorate your view model property with the [DataType] attribute indicating your intent to display it as a multiline text:
[Required(ErrorMessage = "Please Enter Short Desciption")]
[StringLength(200)]
[DataType(DataType.MultilineText)]
public string ShortDescription { get; set; }
and in the view use an EditorFor helper:
#Html.EditorFor(x => x.Product.ShortDescription)
As far as the rows and cols parameters that you expressed concerns in your question about, you could simply use CSS to set the width and height of the textarea. You could for example put this textarea in a div or something with a given classname:
<div class="shortdesc">
#Html.EditorFor(x => x.Product.ShortDescription)
#Html.ValidationMessageFor(x => x.Product.ShortDescription)
</div>
and in your CSS file define its dimensions:
.shortdesc textarea {
width: 150px;
height: 350px;
}