Read The Data From DropDown in ASP.Net MVC3 - asp.net-mvc-3

I am doing the ASP.net MVC 3 (Empty type and not the internet type) with the Database First approach...
What i need is
Step 1:
I just used the dropdown to display the various locations where the company is located. The list comes from the Organization table and Location is only one string field in this Oranization Table,
Step 2:
While the user is doing registration, the dropdown list will show the locations.. Now, user selects India, then this value (Location Name) should store in the UserLogin Table...
Now how to read the value from the dropdown and i hope you understand my question and thanks in advance

I would use view models:
public class RegisterViewModel
{
public string LocationName { get; set; }
public IEnumerable<SelectListItem> Locations { get; set; }
}
then a controller action that will serve the view:
public ActionResult Index()
{
var model = new RegisterViewModel();
model.Locations = new SelectList(dbcontext.Organization_Details, "OName", "OLocation");
return View(model);
}
then the corresponding strongly typed view:
#model RegisterViewModel
#using (Html.BeginForm())
{
#Html.LabelFor(x => x.LocationName)
#Html.DropDownListFor(x => x.LocationName, Model.Locations)
<button type="submit">OK</button>
}
and finally the controller action that will be invoked when the form is submitted:
[HttpPost]
public ActionResult Index(RegisterViewModel model)
{
// model.LocationName will contain the selected location here
...
}

Related

Update single Property on EF4 Entity without having have hidden fields

I am using EF4 (Db First) and I have an entity with a number of non-nullable properties.
In an Edit form (Razor/MVC3), I want to allow the editing of only one of the properties, but not the others.
To get this to work, I am having to put #Html.HiddenFor(...) statements for each of my other properties that can't be nullable, otherwise I get an error on SaveChanges().
Is there a simple way to just have the ID hidden on the view, the property that can be edited, and then update ONLY that property?
All you need to do in this case is to include the ID of the entity you are editing as a hidden field as well as a text field for the property that you actually wanna edit:
#using (Html.BeginForm())
{
#Html.HiddenFor(x => x.ID)
#Html.EditorFor(x => x.PropertyYouWannaEdit)
<button type="submit">Update</button>
}
and then in the corresponding controller action you could retrieve the entity that needs to be edited from your database, update the value of the property that needs editing and save back the changes.
[HttpPost]
public ActionResult Update(SomeEntity model)
{
SomeEntity entityToEdit = db.GetEntity(model.ID);
entityToEdit.PropertyYouWannaEdit = model.PropertyYouWannaEdit;
db.Update(entityToEdit);
return RedirectToAction("Success");
}
But personally I would use a view model and AutoMapper to handle this situation. So I would start by designing a view model representing the requirements of my view and including the properties that needs to be edited only:
public class MyEntityViewModel
{
public int ID { get; set; }
public string Property1ToBeEdited { get; set; }
public string Property2ToBeEdited { get; set; }
...
}
and then have the corresponding view:
#model MyEntityViewModel
#using (Html.BeginForm())
{
#Html.HiddenFor(x => x.ID)
#Html.EditorFor(x => x.Property1ToBeEdited)
#Html.EditorFor(x => x.Property2ToBeEdited)
...
<button type="submit">Update</button>
}
and finally the 2 controller actions (GET and POST):
public ActionResult Update(int id)
{
// Fetch the domain model that we want to be edited from db
SomeEntity domainModel = db.GetEntity(id);
// map the domain model to a view model
MyEntityViewModel viewModel = Mapper.Map<SomeEntity, MyEntityViewModel>(domainModel);
// pass the view model to the view
return View(viewModel);
}
[HttpPost]
public ActionResult Update(MyEntityViewModel model)
{
if (!ModelState.IsValid)
{
// validation failed => redisplay view so that the user can fix the errors
return View(model);
}
// fetch the domain entity that needs to be edited:
SomeEntity entityToEdit = db.GetEntity(model.ID);
// update only the properties that were part of the view model,
// leaving the others intact
Mapper.Map<MyEntityViewModel, SomeEntity>(model, entityToEdit);
// persist the domain model
db.Update(entityToEdit);
// we are done
return RedirectToAction("Success");
}

mvc 3 dynamic Category Dropdown

Ok, I have read a bunch of articles, and I am still lost, so I figure I will put the question out here.
I am trying to create a dynamic dropdown in my "posts" create view. I would like to pull the selectList items from my Categories.sdf, which has a table called categories and two columns, "CategoryID" and "CategoryTitle".
I know I need to pull the items into the viewbag within by "postscontroller" so they can be passed to the view. But I am not sure what this would look like. Again, i'm new to MVC so if i sound like a dope, i apologize.
I know I need to pull the items into the viewbag within by "postscontroller"
Oh no, you don't need to do anything like that.
You could start by defining a view model:
public class PostViewModel
{
[DisplayName("Select a category")]
[Required]
public string SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
that you will populate in your controller:
public class PostsController: Controller
{
public ActionResult Index()
{
var model = new PostViewModel();
model.Categories = db.Categories.ToList().Select(c => new SelectListItem
{
Value = c.CategoryId,
Text = c.CategoryName
});
return View(model);
}
}
and then have a corresponding strongly typed view (~/views/posts/index.cshtml):
#model PostViewModel
#using (Html.BeginForm())
{
#Html.LabelFor(x => x.SelectedCategoryId)
#Html.DropDownListFor(x => x.SelectedCategoryId, Model.Categories, "-- select --")
#Html.ValidationMessageFor(x => x.SelectedCategoryId)
<button type="submit">OK</button>
}

How to Retrieve Page Hyperlinks after Requesting a URL using MVC3?

I have created a very simple view in my MVC3 project that contains a textbox that receives and validates a URL. The controller class is rather simple:
[HttpPost]
public ActionResult Save(ValidationModel model)
{
if (ModelState.IsValid)
{
//Save or whatever
}
return View(model);
}
I'm needing some guidance on how to retrieve the URL entered into the textbox, and subseuquently scan the resulting page for hyperlinks or tags. Once those tags are scanned, I need to return a new view to my user with a list or grid of the tags in alpha order.
Can anyone point me in the correct direction on above steps?
Thanks:)
In your view model you will have a property:
public class ValidationModel
{
[Required]
public string Url { get; set; }
}
and then you will have a corresponding textbox in the view:
#model ValidationModel
#using (Html.BeginForm)
{
#Html.EditorFor(x => x.Url)
<button type="submit">OK</submit>
}
and finally in your POST controller action:
[HttpPost]
public ActionResult Save(ValidationModel model)
{
if (ModelState.IsValid)
{
//Save or whatever
// use model.Url here => it will contain the user input
}
return View(model);
}
Try this:
in your view where your using your model inside your FORM:
#Html.TextBoxFor(m => m.MyHyperLink)
and in your controller you do this:
model.MyHyperLink you can manipulate the string or do what ever you want
easy as that..
hope i helped.

Binding DropdownList and maintain after postback

I am using MVC3. I'm binding the dropdown with the Data coming from a service. But after the page posts back and a filter applies to list, the dropdown shows the filter record value in the grid because I always bind the list coming from the service.
However, I want the dropdown to always show all the Records in the database.
I don't understand your question that clearly. But it seems that it is a dropdown that you have on your view? I also have no idea what you are trying to bind so I created my own, but have a look at my code and modify it to fit in with your scenario.
In your view:
#model YourProject.ViewModels.YourViewModel
On the view there is a list of banks in a dropdown list.
Your banks dropdown:
<td><b>Bank:</b></td>
<td>
#Html.DropDownListFor(
x => x.BankId,
new SelectList(Model.Banks, "Id", "Name", Model.BankId),
"-- Select --"
)
#Html.ValidationMessageFor(x => x.BankId)
</td>
Your view model that will be returned to the view:
public class YourViewModel
{
// Partial class
public int BankId { get; set; }
public IEnumerable<Bank> Banks { get; set; }
}
Your create action method:
public ActionResult Create()
{
YourViewModel viewModel = new YourViewModel
{
// Get all the banks from the database
Banks = bankService.FindAll().Where(x => x.IsActive)
}
// Return the view model to the view
// Always use a view model for your data
return View(viewModel);
}
[HttpPost]
public ActionResult Create(YourViewModel viewModel)
{
if (!ModelState.IsValid)
{
// If there is an error, rebind the dropdown.
// The item that was selected will still be there.
viewModel.Banks = bankService.FindAll().Where(x => x.IsActive);
return View(viewModel);
}
// If you browse the values of viewModel you will see that BankId will have the
// value (unique identifier of bank) already set. Now that you have this value
// you can do with it whatever you like.
}
Your bank class:
public class Bank
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
}
This is simple as it gets. I hope this helps :)
PS: Please remember with future posts, always give as much detail as possible so that we can help you better. Also don't forget to display code samples so that we can see what you have already done. The more details that we can have the better.
When you post the model back to the create[Http Post] action is it not possible to have the list of dropdown list values for the banks binded back to the model. I see that if the model is invalid, you call the code
viewModel.Banks = bankService.FindAll().Where(x => x.IsActive);
to get a list of all the banks again which I assume you need to hit the database again.
Thanks

IEnumerable property with MVC3 EditorTemplate

Similar to this post IEnumerable model property in an ASP.NET MVC 3 Editor Template, I have
Model
public class Student
{
public int StudentId { get; set; }
public string StudentName{ get; set; }
//FYI..Its virtual because of EF relationship
public virtual ICollection<Class> Classes{ get; set; }
}
public class Class
{
public int ClassId { get; set; }
public string ClassName{ get; set; }
}
View - EditStudent
#model Student
#Html.TextBoxFor(m => m.StudentName)
//I get the error for following..see below
#Html.EditorFor(m => m.Classes);
Student/EditorTemplates/Class
#model Class
<div>
#*checkbox here*#
#Html.LabelFor(x => x.ClassName)
</div>
Controller
public ActionResult EditStudent(int id)
{
ViewBag.Classes = repository.GetClasses();
Student student = repository.GetStudent(id);
return View("EditStudent", student);
}
Error in View on statement #Html.EditorFor(m => m.Classes); is..
The model item passes into the dictionary is of type
'System.Collections.Generic.HashSet`1[Class]', but this dictionary
required a model item of type 'Class'.
Basically, what I am trying to achieve is to display the list of all classes available with a checkbox next to it ( I have not reached to that part of code yet). Then check all classes to a student is enrolled and allow to change the selections.
How do I display the list of checkboxes with the given Model.
Should I bind my EditorTemplate with ViewBag.Classes (How?) or ?
I need to get selected checkbox values in Post ActionMethod as well.
I read some posts those suggest to create CheckBoxListHelper, but it should be possible to do with EditorTemplate as I need to display a simple list.
Please suggest. Thanks.
Okay, I figured it out. Thanks to very precise post here
How to provide an EditorTemplate for IEnumerable<MyModel>?
First, I renamed the EditorTemplate to StudentClass - not sure if this has anything to do with binding or not, but I did.
Second, modified EditorTemplate to bind with IEnumerable
#model IEnumerable<Class>
var checked = "";
#foreach (Class class in ViewBag.Classes)
{
if (Model != null)
{
Class class = Model.FirstOrDefault(c => c.ClassId.Equals(class.ClassId));
if (class != null)
{
checked = "checked=checked";
}
}
<input type="checkbox" name="Classes" value="#class.ClassId" #checked />
#class.ClassName
}
And I call the template with name
#Html.EditorFor(m => m.Classes, "StudentClass");
Now in controller's Post method I can get the array of Classes (name of checkboxes).

Resources