how I can make the WebGrid as appears in the picture and get the selected row with the rariobutton
Blessings
Try this
myGrid.Column(header: "Select", format: #<text><input name="chck"
TYPE="RADIO" CHECKED="#item.select" /></text>),
Also check this link http://fiddle.jshell.net/Gt4GH/
This is not a compiled code, try this and let me know if it works :)
You could define view models:
public class UserViewModel
{
public int Id { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class MyViewModel
{
public int? SelectedUserId { get; set; }
public IEnumerable<UserViewModel> Users { get; set; }
}
then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var users = Enumerable.Range(1, 5).Select(x => new UserViewModel
{
Id = x,
Email = "email " + x,
FirstName = "fn " + x,
LastName = "ln " + x,
});
var model = new MyViewModel
{
Users = users
};
return View(model);
}
[HttpPost]
public ActionResult Index(int? selectedUserId)
{
return Content(string.Format("Thank you for selecting user id: {0}", selectedUserId));
}
}
and finally a view:
#model MyViewModel
#{
var grid = new WebGrid(Model.Users);
}
#using (Html.BeginForm())
{
#grid.GetHtml(
columns: grid.Columns(
grid.Column(
header: "Select",
format: #<text>#Html.RadioButtonFor(x => x.SelectedUserId, (int)item.Id)</text>
),
grid.Column("Email"),
grid.Column("FirstName", "First Name"),
grid.Column("LastName", "Last Name")
)
)
<button type="submit">OK</button>
}
Related
Expression in view
i have model in mvc name Flight :
public class Flight
{
public int id { get; set; }
[Required(ErrorMessage = "name is required")]
[StringLength(170)]
public string name { get; set; }
[Required(ErrorMessage = "flight company is required")]
[DisplayName("company Name")]
public string flightCompany { get; set; }
[DataType(DataType.Date)]
public DateTime date { get; set; }
public int idAvaribleClass { get; set; }
[DisplayName("Duration TO")]
public string flightDuration { get; set; }
[DisplayName("Ariport Name")]
[StringLength(200)]
public string airportName { get; set; }
public int idRegisterFlght { get; set; }
public List<FlightDuration> FlightDurations { get; set; }
public List<AvalibleClass> AvalibleClasses { get; set; }
public List<registerFlightProgram> registerFlightPrograms { get; set; }
}
i have action method which search in database about what is user enter in view and return two table by query linq.i want show this table in view :
_Mydb _db = new _Mydb();
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string searchTerm = null, string to = null)
{
var q =
(from c in _db.flights
join p in _db.Durations on c.id equals p.FlightId
where (p.to == to) && (p.fromStar == searchTerm) && (to != null)
select new
{
c = new Flight { id = c.id, name = c.name, flightCompany = c.flightCompany, date = c.date, idAvaribleClass = c.idAvaribleClass, flightDuration = c.flightDuration, airportName = c.airportName, idRegisterFlght = c.idRegisterFlght },
p = new FlightDuration { id = p.id, fromStar = p.fromStar, to = p.to, takeOffTime = p.takeOffTime, expectedTime = p.expectedTime, priceDuration = p.priceDuration, FlightId =p.FlightId}
}).SingleOrDefault();
return View(q);
}
*code view , expression in "#foreach"*
#model IEnumerable<TourismPro.Models.Flight>
#{
ViewBag.Title = "Home Page";
}
#using (Html.BeginForm()){
<form method="post">
<input type="search" name="searchTerm" />
<input type="search" name="to" />
<input type="submit" value="Search By Name" />
**#foreach (var item in Model)**
{
<div>
#item.flightCompany
</div>
}
</form>
}
public class Encapsulated
{
[Required]
public string CategoryId { get; set; }
}
public class Category
{
public string ID { get; set; }
public string CategoryName { get; set; }
}
public class Test
{
public Encapsulated encapsulated { get; set; }
private IEnumerable<Category> categories;
public IEnumerable<Category> Categories
{
get { return
new List<Category>{new Category{ID="1",CategoryName="abc"}}; }
set { categories = value; }
}
}
#using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "Post" }))
{
#Html.DropDownListFor(
x => x.encapsulated.CategoryId,
new SelectList(Model.Categories, "ID", "CategoryName"),
"-- Please select a category --"
)
#Html.ValidationMessageFor(x => x.encapsulated.CategoryId)
<input type="submit" value="Submit Form" />
}}
Why doesn't client validation work on dropDownList. If I place
[Required]
public string CategoryId { get; set; }
directly inside my Test class and change the view to
#Html.DropDownListFor( x => x.CategoryId,
new SelectList(Model.Categories, "ID", "CategoryName"), "-- Please select a category --" ) #Html.ValidationMessageFor(x => x.CategoryId)
client side validation starts working...
I'm trying to display a dropdown list in a webgrid, but I can't get it to work :(
I'm getting the following error: (on last column in the view)
The best overloaded method match for
'System.Web.Helpers.WebGrid.Column(string, string,
System.Func, string, bool)' has some invalid
arguments \Visual Studio
2010\Projects\foo\bar\Views\Admin\ManageRoles.cshtml
Hope you can make sense of the code.
Model:
public class UserViewModel
{
[Display(Name = "User name")]
public string Name { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
public string Role { get; set; }
public IEnumerable<SelectListItem> Roles1 { get; set; }
public string Email { get; set; }
}
Controller
public ActionResult ManageRoles()
{
var users = Membership.GetAllUsers().Cast<MembershipUser>().Select(x => new UserViewModel
{
Name = x.UserName,
Email = x.Email,
Roles1 = RolesList,
Role = Roles.GetRolesForUser(x.UserName).FirstOrDefault()
});
ViewBag.Roles = users;
return View(users);
}
public IEnumerable<SelectListItem> RolesList
{
get
{
return Roles.GetAllRoles()
.Select(x => new SelectListItem
{
Value = x,
Text = x
})
.ToList();
}
}
View:
#model IEnumerable<UserViewModel>
#{
ViewBag.Title = "ManageRoles";
var grid = new WebGrid(source: Model, defaultSort: "Name");
}
<h2>ManageRoles</h2>
#grid.GetHtml(
columns: grid.Columns(
grid.Column("Name"),
grid.Column("Email"),
grid.Column("ListItemId", "Role", format: ((item) => Html.DropDownListFor(item.Role, item.Roles1)))
)
)
Given I have a Model object like ...
public class MyModel
{
public int SomeProperty { get; set; }
public int SomeOtherProperty { get; set; }
public IList<DeliveryDetail> DeliveryDetails { get; set; }
}
public DeliveryDetail
{
public string Description { get; set; }
public bool IsSelected { get; set; }
}
and I pass it through to a View like this ...
// Controller
public ActionResult Index()
{
MyModel myModel = Factory.CreateModelWithDeliveryDetails(x);
return View(myModel);
}
How would I render / bind a set of radio buttons (in the view)? Using the following code doesn't post the data back:
#foreach(var deliveryDetail in #Model.DeliveryDetails)
{
#deliveryDetail.Description
#Html.RadioButtonFor(x => deliveryDetail, false)
}
Selections in a radio button list are mutually exclusive. You can select only a single value. So binding a radio button list to a property of type IEnumerable doesn't make any sense. You probably need to adapt your view model to the requirements of the view (which in your case is displaying a radio button list where only a single selection can be made). Had you used a checkbox list, binding to an IEnumerable property would have made sense as you can check multiple checkboxes.
So let's adapt the view model to this situation:
Model:
public class MyModel
{
public string SelectedDeliveryDetailId { get; set; }
public IList<DeliveryDetail> DeliveryDetails { get; set; }
}
public class DeliveryDetail
{
public string Description { get; set; }
public int Id { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyModel
{
DeliveryDetails = new[]
{
new DeliveryDetail { Description = "detail 1", Id = 1 },
new DeliveryDetail { Description = "detail 2", Id = 2 },
new DeliveryDetail { Description = "detail 3", Id = 3 },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyModel model)
{
// Here you will get the id of the selected delivery detail
// in model.SelectedDeliveryDetailId
...
}
}
View:
#model MyModel
#using (Html.BeginForm())
{
foreach (var deliveryDetail in Model.DeliveryDetails)
{
#deliveryDetail.Description
#Html.RadioButtonFor(x => x.SelectedDeliveryDetailId, deliveryDetail.Id)
}
<button type="submit">OK</button>
}
You need another property for posted value::
public class MyModel
{
public int SomeProperty { get; set; }
public int SomeOtherProperty { get; set; }
public IList<DeliveryDetail> DeliveryDetails { get; set; }
public DeliveryDetail SelectedDetail { get; set; }
}
And in view:
#foreach(var deliveryDetail in #Model.DeliveryDetails)
{
#deliveryDetail.Description
#Html.RadioButtonFor(x => x.SelectedDetail, deliveryDetail)
}
In order this to work DeliveryDetail has to be Enum.
I want to pass three field to my controller using RemoteAttribute. How can i do it?
public int ID1 { get; set; }
public int ID2 { get; set; }
[Remote("CheckTopicExists", "Groups", AdditionalFields = "ID1", ErrorMessage = " ")]
public string Topic { get; set; }
public ActionResult CheckTopicExists(string topic, int ID1,int ID2)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
How can i pass three field to that function?
You could separate them by comma:
AdditionalFields = "ID1, ID2"
Full example:
Model:
public class MyViewModel
{
public int ID1 { get; set; }
public int ID2 { get; set; }
[Remote("CheckTopicExists", "Home", AdditionalFields = "ID1, ID2", ErrorMessage = " ")]
public string Topic { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
ID1 = 1,
ID2 = 2,
Topic = "sample topic"
});
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
public ActionResult CheckTopicExists(MyViewModel model)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
View:
#model MyViewModel
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
#using (Html.BeginForm())
{
#Html.EditorFor(x => x.ID1)
#Html.EditorFor(x => x.ID2)
#Html.LabelFor(x => x.Topic)
#Html.EditorFor(x => x.Topic)
#Html.ValidationMessageFor(x => x.Topic)
<input type="submit" value="OK" />
}
Be aware of sending dates, sometimes controller receive date in a wrong format: was dd/mm/yyyy, receive mm/dd/yyyy
Instead of using
public ActionResult CheckTopicExists(MyViewModel model)
If you use
public ActionResult CheckTopicExists(FormCollection Collection)
then you can reuse the code for other classes as well