MVC Html.CheckBox list and Jquery Post - asp.net-mvc-2

my code is
<% using (Html.BeginForm())
{%>
<table>
<tr>
<th>
LabelID_FK
</th>
<th>
LabelName
</th>
<th>
LabelIsDocument
</th>
</tr>
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%: item.LabelID_FK %>
</td>
<td>
<%: item.LabelName %>
</td>
<td>
<%-- <input type="checkbox" value="df" id="chk" onclick="check()" />--%>
<%=Html.CheckBox("chk_"+ item.LabelID_FK)%>
</td>
</tr>
<% } %>
</table>
<p>
<input type="button" value="submit" id="btn" />
</p>
which show checkbox list for document label which user can select it .
i want pass data list which user select checkbox it use jquery post
what i do?

i use this code when user click on button and work very good
[HttpPost]
public ActionResult DocumentLabel(FormCollection model)
{
for (int i = 0; i < model.Count; i++)
{
AriaCRMEntities aria = new AriaCRMEntities();
DocumentLabel label = new DocumentLabel();
string lbl = model[i].ToString();
string[] check = lbl.Split(',');
bool chk = Convert.ToBoolean(check[0]);
string name = model.Keys[i].ToString();
string[] n = name.Split('_');
string lblid = n[1];
if (chk)
{
label.LabelID_FK = Int32.Parse(lblid);
Guid id = Guid.NewGuid();
label.DocumentID_FK = id;
aria.DocumentLabels.AddObject(label);
aria.SaveChanges();
}
}
return Content("0ok");
}
but i want jquery post i need array check box whit select it to pass it to controller?

Related

Update record on database in MVC4

need some help here..
Aim: Update record on database in MVC4
I have a Accordian view with two buttons #1.Edit #2.save..
Till now what had done is..
using following code i have fetch data from database to corresponding text boxes.
Step 1: Data filled in textboxes are property set as readonly once edit button clicked text boxes will set as editable.
Step 2:if i change data and click save button that should update on database
Problem:
While updating the data in the database updated data is adding in the new row as a new data.
But i need the existing data should be updated
View:
<body>
<div id='cssmenu'>
<ul>
<li class='active'></li>
<li class='has-sub'>
<a href='#'><span>Profile</span></a>
<ul>
<form method="post" >
<table>
<tr>
<td>
#Html.DisplayNameFor(model => model.FirstName)
</td>
<td>
#Html.TextBoxFor(m => m.FirstName, new { #readonly = "readonly" })
#*#Html.EditorFor(model => model.FirstName)*#
#Html.ValidationMessageFor(model => model.FirstName)
</td>
</tr>
<tr>
<td>
#Html.DisplayNameFor(model => model.LastName)
</td>
<td>
#Html.TextBoxFor(m => m.LastName, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.LastName)
</td>
</tr>
<tr>
<td>
#Html.DisplayNameFor(model => model.EmailID)
</td>
<td>
#Html.TextBoxFor(m => m.EmailID, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.EmailID)
</td>
</tr>
<tr>
<td>
#Html.DisplayNameFor(model => model.MobileNumber)
</td>
<td>
#Html.TextBoxFor(m => m.MobileNumber, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.MobileNumber)
</td>
</tr>
</table>
<input type="button" id="btn" name="Edit" value="Edit"/>
<input type="submit" name="Save" id="Save" />
#*<input type="submit" name="Save" value="Save" onclick="location.href='#Url.Action("Save", "CU")'" />*#
</form>
</ul>
</li>
<li class='has-sub'>
<a href='#'><span>Change Password</span></a>
<ul>
<li><a href='#'><span>Company</span></a></li>
<li class='last'><a href='#'><span>Contact</span></a></li>
</ul>
</li>
<li class='has-sub'>
<a href='#'><span>Add Customer</span></a>
<ul>
<li><a href='#'><span>Company</span></a></li>
<li class='last'><a href='#'><span>Contact</span></a></li>
</ul>
</li>
</ul>
</div>
</body>
#section scripts
{
<script type="text/javascript">
$("#btn").click(function () {
$("#FirstName").removeAttr("readonly");
$("#LastName").removeAttr("readonly");
$("#EmailID").removeAttr("readonly");
$("#MobileNumber").removeAttr("readonly");
});
</script>
}
Controller
public ActionResult AccountPanel(int id, string Save, string FirstName)
{
var profile = (from s in db.tblUsers
where s.UserTypeId == 3 && s.UserID == id
select new Profile
{
FirstName = s.FirstName,
LastName = s.LastName,
EmailID = s.EmailID,
MobileNumber = s.MobileNumber
}).FirstOrDefault();
if (Save != null)
{
using (var context = new SYTEntities())
{
var s = context.tblUsers.Where(a => a.UserID == id).FirstOrDefault();
s.FirstName = FirstName;
s.LastName = profile.LastName;
s.EmailID = profile.EmailID;
s.MobileNumber = profile.MobileNumber;
context.tblUsers.Add(s);
context.SaveChanges();
}
}
return View(profile);
}
To update data in the database please change to below code.
if (Save != null)
{
using (var context = new SYTEntities())
{
var s = context.tblUsers.Where(a => a.UserID == id).FirstOrDefault();
s.FirstName = FirstName;
s.LastName = profile.LastName;
s.EmailID = profile.EmailID;
s.MobileNumber = profile.MobileNumber;
context.SaveChanges();
}
}
remove context.tblUsers.Add(s); from your code
using (var context = new SYTEntities())
{
var s = context.tblUsers.Where(a => a.UserID == id).FirstOrDefault();
s.FirstName = FirstName;
s.LastName = profile.LastName;
s.EmailID = profile.EmailID;
s.MobileNumber = profile.MobileNumber;
// SET STATE TO CHANGED
db.Entry(tblUsers).State = EntityState.Modified;
context.SaveChanges();
}

Passing String value to controller on button click MVC2

I am trying to send some value to controller on button click
Here is the view
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Customers</h2>
<table>
<tr style=" background-color:White; font-style:normal; font-size:x-large;">
<td>S#</td> <td>Name</td> <td>Email</td> <td>Phone</td> <td>Edit</td>
<%int i = 1;
string name, id, phone, email;
%>
</tr>
<% foreach (var clientsModel in ViewData["AllClients"] as List<MvcApplication5.Models.ClientsModels>){ %>
<tr style=" background-color:black; font-style:oblique; color:Wheat; font-size:large;">
<td><%:i %></td>
<% name = clientsModel.Name;
phone = clientsModel.Phone;
id = clientsModel.UserID;
email = clientsModel.Email; %>
<td>
<label id="Name"><%= clientsModel.Name %></label>
</td>
<td>
<label id="Email"><%= clientsModel.Email %></label>
</td>
<td>
<label id="Phone"><%= clientsModel.Phone %></label>
</td>
<td><button id="edit" >Edit</button></td>
</tr>
<% i++;
} %>
</table>
</asp:Content>
and here is the controller to which i want to send the values
public ActionResult Edit(string name, string id, string phone, string email)
{
ViewData["name"] = name;
ViewData["phone"] = phone;
ViewData["id"] = id;
ViewData["email"] = email;
return View();
}
i want to send the values of name, phone, email and id to controller...
if you are using Ajax
var dataPost = { 'id': id, 'val': val };
$.ajax({
type: 'POST',
url: '/Controller/Action',
data: JSON.stringify(dataPost),
contentType: 'application/json',
success: function () {
alert("succes");
},
error: function () {
alert("error");
}
});

MVC : Model does not submit for multiple forms

This is related to ASP.Net MVC 2
I have a model (MoviesForAll) bound to my view and this model has a collection of class ICollection. I want my user to buy single ticket at a time by clicking submit button 'Buy this ticket' so I have placed a button besides each row representing the ticket details. This lead to following sequence
<%#Page Title="title" Language="C#" MasterPageFile="~/Views/Shared/MyMaster.Master"
Inherits="System.Web.Mvc.ViewPage<OnlineBooking.Movies.MoviesForAll>">
<Table>
<% for(i=0; i<Model.Tickets.count; i++)
{ %>
<tr>
<% using (Html.BeginForm(myaction(), FormMethod.Post, new {id="myform"}))
{ %>
<td>
<%= Model.tickets[i].ticketID %>
<%= Html.HiddenFor(m=>m.tickets[i].ticketID) %>
</td>
<td>
<%= Model.tickets[i].seatNo %>
<%= Html.HiddenFor(m=>m.tickets[i].seatNo) %>
</td>
...
...
<td>
<input type="submit" value="buy this ticket" runat="server">
</td>
<% } %>
</tr>
<% } %>
</table>
This creates a form for each row of tickets having single submit button in that form.
The problem is, when I submit first row (having index 0) by clicking the button, it gets submitted properly and I can see the values in controller method. But no other row gets through to controller even if I have used hidden fields to bind it.
Am I missing anything here specific to index or something?
Thanks in advance..
I would suggest having one form for all the rows, then on each row use the button element instead of an input as follows:
<button type="submit" value="<%= Model.tickets[i].ticketID %>" name="buyticket">Buy this ticket</button>
You should have a parameter on your controller action called buyticket and that should have the ticket id of the button which was clicked
How about the following:
<table>
<% for(i = 0; i < Model.Tickets.Count; i++) { %>
<tr>
<% using (Html.BeginForm("myaction", FormMethod.Post, new { id = "myform" })) { %>
<td>
<%= Model.tickets[i].ticketID %>
</td>
<td>
<%= Model.tickets[i].seatNo %>
</td>
...
...
<td>
<%= Html.Hidden("TicketId", Model.tickets[i].ticketID) %>
<%= Html.Hidden("SeatNumber", Model.tickets[i].seatNo) %>
<input type="submit" value="buy this ticket" />
</td>
<% } %>
</tr>
<% } %>
</table>
and then:
public class TicketToPurchaseViewModel
{
public int TicketId { get; set; }
public int SeatNumber { get; set; }
}
and the action:
[HttpPost]
public ActionResult myaction(TicketToPurchaseViewModel ticket)
{
...
}
Remark: notice that I have removed the runat="server" attribute from the submit button as well because this is something that you definitely don't want to see in an ASP.NET MVC application.

MVC2 code conversion in Razor

I am using someones code for paging. His code is in MVC 2 and I want it in MVC3 Razor. Problem is with syntax.
Below is the code in mvc need someone to fix syntax for razor please.
Problem is in this line
IList<Customer> customers = (IList<Customer>)Model.Data;
//Can't use Model.Data directly. Doesn't pick up generic type.
IList<Customer> customers = (IList<Customer>)Model.Data;
foreach (Customer item in customers) { %>
<tr onclick="onRowClick(<%= item.ID %>)">
<td>
<%= Html.ActionLink("Edit", "Edit", new { id=item.ID}) %> |
<%= Html.ActionLink("Delete", "Delete", new { id=item.ID })%>
</td>
<td>
<%= Html.Encode(item.ID) %>
</td>
<td>
<%= Html.Encode(item.FirstName) %>
</td>
</tr>
<% } %>
The line could be translated like this:
# {
IList<Customer> customers = (IList<Customer>)Model.Data;
}
and then:
#foreach (Customer item in customers) {
<tr onclick="onRowClick(#item.ID)">
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID })
#:|
#Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
<td>
#item.ID
</td>
<td>
#item.FirstName
</td>
</tr>
}
I would also benefit from this migration to improve this code. Currently you are using loops in your views which are ugly and could be replaced with display templates.
So, in your main view:
#Html.DisplayFor(x => x.Data)
and in ~/Views/Home/DisplayTemplates/Customer.cshtml:
#model YourApp.Models.Customer
<tr onclick="onRowClick(#Model.ID)">
<td>
#Html.ActionLink("Edit", "Edit", new { id = Model.ID })
#:|
#Html.ActionLink("Delete", "Delete", new { id = Model.ID })
</td>
<td>
#Model.ID
</td>
<td>
#Model.FirstName
</td>
</tr>

How to filter the dropdown list by using other dropdown list in asp.net MVC web-application

everyone, I encounter a problem when I try to filter the drop down list.
The situation is I wish to filter the Agent dropdown list by using the Company dropdown list in same view/form. Since I need to display the Agents that only belong to the selected Company. But I have no idea to do that.
Any solution, please?
First add Method in Controller as follows
MvcApplication2.Models.MySampleDBEntities db = new Models.MySampleDBEntities();
public ActionResult SearchNames(string ddlcontent)
{
var list = new List<string>();
var nameqry = from n in db.Images
select n.PlayerName;
list.AddRange(nameqry.Distinct());
ViewBag.ddlcontent = new SelectList(list);
var names = from m in db.Images
select m;
if (string.IsNullOrEmpty(ddlcontent))
return View(names);
else//Filter content basedon dropdownlist selected item
return View(names.Where(s => s.PlayerName.Contains(ddlcontent)));
}
then bind it to view as follows
#model IEnumerable<MvcApplication2.Models.Image>
#{
ViewBag.Title = “SearchNames”;
}
<h2>SearchNames</h2>
#using (#Html.BeginForm(“SearchNames”, “Names”, FormMethod.Get))
{
#Html.DropDownList(“ddlcontent”, “All”)<input type=”submit” value=”Filter” />;
}
<table border=”4″ style=”border: medium dashed #FF0000″>
<tr>
<th>
PlayerName
</th>
<th>
Play
</th>
<th>
CountryName
</th>
<th>
Image
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.PlayerName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Play)
</td>
<td>
#Html.DisplayFor(modelItem => item.CountryName)
</td>
<td>
<img src=”#item.ImagePath” height=”100″ width=”100″/>
</td>
</tr>
}
</table>
2 options really...either split the server-based form post into multiple steps, or use jquery to handle this behavior JIT