Passing String value to controller on button click MVC2 - asp.net-mvc-2

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");
}
});

Related

Is there any way to have Controller, ViewModel and View without Model? It's for an Index only view

What I want to do is a parametrized report, i would love to use SSRS or other fancy tools for this but it's sort of dangerous at this point because i don't really want to mess around with the company server and I dont have much time; Also If it's a tool it should be a free and light tool and i didn't find one by now.
So, my idea is making a simple controller with Index that will return a List to View according to parameters and the View will use that ViewModel as Model then the users can export that list to CSV or PDF, the problem is: MVC is asking for a real db model to complete the scaffolding, how can this be done then?
Controller (I call an stored proc here)
public class ReporteEntregasPresentacionController : Controller
{
private EntregaMedicamentosEntities db = new EntregaMedicamentosEntities();
public ActionResult Index(DateTime DateFrom, DateTime DateTo)
{
ReporteEntregasPresentacionViewModel rep = new ReporteEntregasPresentacionViewModel();
string sqlQuery = "[dbo].[spEntregasPorPresentacion] ({0},{1})";
Object[] parameters = { DateFrom, DateTo };
rep.LstEntregasPresentacionViewModel = db.Database.SqlQuery<ItemEntregasPresentacionViewModel>(sqlQuery, parameters).ToList();
return View(rep);
}
}
ViewModel:
public class ReporteEntregasPresentacionViewModel
{
public int index;
public List<ItemEntregasPresentacionViewModel> LstEntregasPresentacionViewModel;
}
public class ItemEntregasPresentacionViewModel {
public string idProducto { get; set; }
public string Descripcion { get; set; }
public string EntregasTotales { get; set; }
}
I don't have a View now but i should be something like this:
#model EntregaMedicamentos.Models.ReporteEntregasPresentacionViewModel
<link href="~/Content/css/styles.css" rel="stylesheet" />
#{
ViewBag.Title = "ReporteEntregasPresentacion";
}
<h2>ReporteEntregasPresentacion</h2>
#using (Html.BeginForm("Index", "Entrega", FormMethod.Post))
{
<div class="card text-white bg-secondary">
<h5 class="card-header">Search</h5>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<div class="input-group">
#Html.TextBox("DateFrom", ViewBag.currentFilter1 as DateTime?, new { #class = "form-control", placeholder = "Desde fecha", #readonly = "true", type = "datetime" })
#Html.TextBox("DateTo", ViewBag.currentFilter2 as DateTime?, new { #class = "form-control", placeholder = "Hasta fecha", #readonly = "true", type = "datetime" })
<button id="Submit4" type="submit" style='font-size:22px ;color:blue'><i class='fas fa-search'></i></button>
</div>
</div>
</div>
</div>
</div>
}
<br>
<table class="table table-striped ">
<tr class="table-primary">
<th>
Código
</th>
<th>
Producto
</th>
<th>
Entregas Totales
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.idProducto)
</td>
<td>
#Html.DisplayFor(modelItem => item.Descripcion)
</td>
<td>
#Html.DisplayFor(modelItem => item.Valor)
</td>
</tr>
}
</table>
I ended up creating a real table/model and then it worked fine with the viewmodel. Thanks.

How to add "handleRemove" function to Graphql both Query and Delete Mutation?

My Application is using React, Apollo client 2, Apollo Server and MongoDB as the database.
I try to add "handleRemove" function to query page that I use React.
But when I click "Delete" button, I get "deleteCustomer" is not the function.
Here is my code of this page, please help to find out the solution.
import React, { Component } from 'react';
import gql from 'graphql-tag';
import { graphql, compose } from 'react-apollo';
import { Link } from 'react-router-dom';
import { Button, Alert } from 'react-bootstrap';
import Loading from '../components/Loading';
class Customers extends Component {
handleRemove = async (customerID) => {
const result = await this.props.deleteCustomer({
variables: {
_id: customerID,
},
})
}
render() {
const { data: {loading, CustomersList }, match, history } = this.props;
return ( !loading ? (
<div className="Customers">
<h2><p className="text-center">Customer List</p></h2>
<Button><Link to={`/customers/new`}>Add Customer</Link></Button>
<br />
<br />
{CustomersList.length ?
<table className="zui-table zui-table-rounded">
<thead>
<tr>
<th><p className="text-center">List</p></th>
<th>
</th>
<th><p className="text-center">Salution</p></th>
<th><p className="text-center">Firstname</p></th>
<th><p className="text-center">Lastname</p></th>
<th><p className="text-center">Nickname</p></th>
<th><p className="text-center">Email</p></th>
<th><p className="text-center">Phone</p></th>
<th><p className="text-center">Mobile</p></th>
<th />
<th />
</tr>
</thead>
<tbody>
{CustomersList.map(({ _id, salution, firstname, lastname, nickname, email, phone, mobile, total_spent, createdAt, updatedAt }, index) => (
<tr key={_id}>
<td>{index+1}</td>
<td>
</td>
<td>{salution}</td>
<td>{firstname}</td>
<td>{lastname}</td>
<td>{nickname}</td>
<td>{email}</td>
<td>{phone}</td>
<td>{mobile}</td>
<td>
<p className="text-center">
<button className="btn btn-info btn-sm"
onClick={() => history.push(`${match.url}/${_id}/edit`)}
>Edit</button>
</p>
</td>
<td>
<p className="text-center">
<button className="btn btn-danger btn-sm"
onClick={() => this.handleRemove(_id)}
>Delete</button>
</p>
</td>
</tr>
))}
</tbody>
</table> : <Alert bsStyle="warning">Nobody registered yet!</Alert>}
</div>
) : <Loading /> );
}
}
export const customersListQuery = gql`
query customersListQuery {
CustomersList {
_id
salution
firstname
lastname
nickname
email
phone
mobile
total_spent
createdAt
updatedAt
}
}
`;
export const deleteCustomer = gql`
mutation deleteCustomer($_id: ID!) {
deleteCustomer(_id: $_id) {
_id
}
}
`;
export default compose(
graphql(customersListQuery),
graphql(deleteCustomer, { name: deleteCustomer }),
)(Customers);
The name of the mutation should be a string. The quotes are missing:
...
export default compose(
graphql(customersListQuery),
graphql(deleteCustomer, { name: "deleteCustomer" }),
)(Customers);

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();
}

MVC Html.CheckBox list and Jquery Post

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?

Collections.Generic.Dictionary<TKey,Tvalue> model binding from Viewmodel to controller

i have this problem :
when i try to post submit from a View to a httppost actionResult i get always a null value.
this is my code :
public class WhiteListViewModel
{
public string Badge { get; set; }
public IEnumerable<string> Selezioni { get; set; }
public IEnumerable<bool> Abilitazioni { get; set; }
}
public ActionResult WhiteList()
{
return View( "Whitelist", MasterPage, new WhitelistViewModel());
}
[HttpPost]
public ActionResult WhiteListp(IEnumerable<WhiteListViewModel> Whitelist )
{
bool[] abilitato = new bool[Whitelist.Single().Abilitazioni.Count()];
string[] selezione = new string[Whitelist.Single().Selezioni.Count()];
...
}
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/SiteR.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<_21112010.ViewModel.WhiteListViewModel>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
WhiteList
</asp:Content
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>WhiteList</h2>
<table style="width:100%;">
<thead>
</thead>
<tbody >
<%using ( Html.BeginForm( ) )
{%>
<% foreach ( var item in Model ){%>
<tr style="width:100%;">
<td >
<%: item.Badge%>
</td>
<%foreach ( var abit in item.Abilitazioni ){%>
<td >
<%: Html.CheckBoxFor(c=>abit/*, new { onchange = "this.form.submit();" } */ )%>
<%: Html.ValidationMessageFor(c => abit) %>
</td>
<% } %>
<%} %>
<td style=" width:1px;" >
<%: Html.HiddenFor(model=>item.Badge) %>
<% foreach (var sel in item.Selezioni) {%>
<%: Html.HiddenFor(c=>sel) %>
<%} %>
</td>
</tr> <%}%>
</tbody>
<tfoot>
</tfoot >
</table>
<input type="submit" value="Salva ed Esci" style = "background-color:Gray; color:#F6855E; font-weight:bold; border:1px solid black; height:20px;" />
<%:Html.ActionLink( "Aggiungi Badge", "AggiungiBadge")%>
<% } %>
</div>
</asp:Content>
where am I doing wrong?
The binding process will attempt to map the IEnumerable to the parameter Whitelist of the HttpPost action. However, I'm fairly sure that this is failing because the binding process has no information to tie the submitted fields to the expected parameter "Whitelist".
You have a few options:
Try using TryUpdateModel() in your action;
Creating a custom ModelBinder. This will allow you to interogate the submitted Model and build your IEnumerable prior to it being passed to the action parameter;
You could interogate the submitted fields using the FormCollection object from within the action. This is a little messy and not ideal;
Simplify your view.
Personally, I would look at the ModelBinder. If anything, this would give you a better insight into why the Model may not be binding to the action parameter.