How to validate dropdown in asp.net mvc2.0? - asp.net

I am using asp.net mvc 2.0.I have to validate my dropdownlist after clicking save button.
this is my view code.
<%using (Html.BeginForm("Save", "Home", FormMethod.Post, new { id = "Save" }))
{
%>
<table>
<tr>
<td>
<%:Html.TextBoxFor(m => m.EmployeeName)%>
</td>
</tr>
<tr>
<td>
<%:Html.DropDownListFor(m => m.ProjectModel, new SelectList(Model.ProjectModel, "Id", "ProjectName"), new { #id = "ddlProject"})%>
</td>
</tr>
<tr>
<td>
<input id="btnSave" type="button" value="Save" />
</td>
</tr>
</table>
<center>
<div id="result">
<%Html.RenderPartial("~/Views/PartialViews/partialpage.ascx");>
</div>
</center>
</table>
<%} %>
and my java script code is:
$(document).ready(
function () {
$('#btnSave').click(function () {
$.ajax(
{
cache: false,
async: true,
type: "POST",
url: $('#Save').attr('action'),
data: $('#Save').serialize(),
success: function (data) {
$('#result').html(data);
},
error: function (data) {
}
});
});
});
here am using
input type="button"
because i have to return partial view after submit save button.
can anyone tell how to validate my dropdown??

I write this as follow in Asp.Net Mvc4. I think that perhaps it is same in Mvc2.
#Html.DropDownListFor(model => model.Contract.ContractStatusId, new SelectList(Model.ContractStatus, "ContractStatusId", "Name"), "-- Select Status --", new { data_form = "select2", #style = "width: 200px;" })
#Html.ValidationMessageFor(model => model.Contract.ContractStatusId)

Related

Inserting data using ado.net via ajax

i am having trouble in finding the problem. I was inserting product record via ado.net and it worked fine. Now i tried ajax for doing it in a more better way . but i am having trouble since the code never runs the function intended to run when i click button via ajax. so need ur help. Thanks. here is the code:
//this is my home.aspx page
$(document).ready(function () {
$("#submit").click(function () {
alert("you clicked");
$.ajax({
type: "POST",
contentType: "application/json",
url: "home.aspx/insert",
dataType: "json",
// data: "{'Name':'" + document.getElementById('name').value + "'}",
data:"{}",
//async: false,
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
})
});
</script>
//////////////////////////////////
<form id="form1" runat="server">
<div>
<table>
<tr>
<td><label>Product Name</label></td>
<td> <asp:TextBox runat="server" id="name"></asp:TextBox></td>
</tr>
<tr>
<td><label>Product Code</label></td>
<td><asp:TextBox runat="server" id="code"></asp:TextBox></td>
</tr>
<tr>
<td><label>Product Category</label></td>
<td><asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Gadgets</asp:ListItem>
<asp:ListItem>Vehicles</asp:ListItem>
<asp:ListItem>Garments</asp:ListItem>
<asp:ListItem>Eatables</asp:ListItem>
<asp:ListItem>Furniture</asp:ListItem>
</asp:DropDownList></td>
</tr>
<tr>
<td><label>Expiry date</label></td>
<td><asp:TextBox runat="server" TextMode="Date" id="dt"></asp:TextBox></td>
</tr>
<tr>
<td><label>Product price</label></td>
<td><asp:TextBox runat="server" id="price"></asp:TextBox></td>
</tr>
<tr>
<td><label>Product Image</label></td>
<td> <asp:FileUpload ID="file_image" runat="server" /></td>
<td> </td>
<td><asp:Label runat="server" id="showtext"></asp:Label></td>
</tr>
<tr></tr>
<tr></tr>
<tr>
<td></td>
<%--<asp:Button runat="server" OnClick="submit" Text="Submit" BackColor="White" Width="100px" />--%>
<td> <input type="button" style=" width:100px;" value="Submit" id="submit" /> </td>
</tr>
</table>
</div>
<asp:Label ID="res" runat="server"></asp:Label>
</form>
///////////////////////////////////////////////
//this is my home.aspx.cs page :
public void insert()
{
if (file_image.HasFile)
{
string ext = System.IO.Path.GetExtension(file_image.FileName);
if (!ext.Equals(".jpg"))
{
showtext.Text = "Please select correct file format i.e jpg or jpeg";
showtext.ForeColor = System.Drawing.Color.Purple;
}
else
{
file_image.SaveAs(Server.MapPath("~/Uploads/" + file_image.FileName));
showtext.Text = "File uploaded";
showtext.ForeColor = System.Drawing.Color.Green;
productclass pc = new productclass();
pc.Pr_name = name.Text;
pc.Code = code.Text;
pc.Category = DropDownList1.SelectedValue;
pc.Expiry = Convert.ToDateTime(dt.Text);
pc.Price = Convert.ToInt32(price.Text);
pc.Pr_image = file_image.FileName;
dalinsert di = new dalinsert();
bool flag = di.insert(pc);
if (flag.Equals(true))
{
res.Text = "data inserted";
//Thread.Sleep(10000);
// Response.Redirect("home.aspx");
}
else
{
res.Text = "issue in inserting data";
}
}
}
else
{
showtext.Text = "Please select file";
showtext.ForeColor = System.Drawing.Color.Red;
}
}

Select multiple data from table in view asp.net MVC4 Razor

i have following View where user has a table of products and i need select all data where "Quantity > 0" default is 0. But i dont know how can i get collection of data from table. Thanks for respond.
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Produkty</legend>
<table>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(model => item.Product.Name)
</td>
<td>
#Html.DisplayFor(model => item.Product.Price)
</td>
<td>
#Html.EditorFor(model => item.Quantity)
</td>
</tr>
}
<p>
<input type="submit" value="Orders" />
</p>
</table>
</fieldset>
}
//Controller
public ActionResult Index()
{
List<ProductListViewModel> productList = new List<ProductListViewModel>();
foreach (var item in db.Products.ToList())
{
ProductListViewModel model = new ProductListViewModel();
model.Product = item;
model.Quantity = 0;
productList.Add(model);
}
return View(productList);
}
Since you're using Html.EditorFor, things are easy.
Put productList as parameter in your Index Action(for Post), MVC will auto combine form data to productList Object, so you just need to filter the quantity in server side with a loop.
Of cause, to identify the product object, you'd better also add a hidden ID in your view.
<table>
#for(int i = 0; i<Model.Count; i++) {
<tr>
<td>
#Html.HiddenFor(model => Model[i].Product.ID)
#Html.DisplayFor(model => Model[i].Product.Name)
</td>
<td>
#Html.EditorFor(model => Model[i].Quantity)
</td>
</tr>
}
[HttpPost]
public ActionResult Index(List<ProductListViewModel> productList)
{
\\...
}

customize popup window in telerik grid in mvc

i have to display customize popup window in telerik grid because i cannot display all values in grid so i want when user click on grid edit button and according to particular row datakey
fetch data from table and display those records in popup window and i want to open that window when user click on grid button not on my checkout button so what can i do
view
<%# Page Title="" Language="C#" MasterPageFile="~/Content/JobSeekers.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<ITClassifieds.ViewModels.workexperience>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
trial
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function onRowSelected(e) {
var ordersGrid = $('#Grid').data('tGrid');
var resexpid = e.row.cells[0].innerHTML;
// update ui text
$('#rexsepid').text(resexpid);
// rebind the related grid
// ordersGrid.rebind({
// resexpid: resexpid
// });
var window = $("#Window").data("tWindow");
window.center().open();
}
function closeWindow() {
var window = $("#Window").data("tWindow");
window.close();
var undoButton = $('#undo');
undoButton.show();
}
function openWindow() {
var window = $("#Window").data("tWindow");
window.center().open();
// var ordersGrid = $('#Grid').data('tGrid');
// var resexpid = ordersGrid.row.cells[0].innerHTML;
// $('#rexsepid').text(resexpid);
// alert(resexpid);
}
function viewDetails(activityId) {
//....Do stuff here...
alert(activityId);
}
</script>
<h2>trial</h2>
<%=Html.Telerik().Grid(Model).Name("Grid").DataKeys(keys => keys.Add(m => m.resexpid))
.Columns(columns=>
{
columns.Bound(m => m.resexpid).Width(100);
columns.Bound(m => m.company).Width(100);
//columns.Bound("Title").Width(100);
columns.Bound(m=>m.title).Width(200);
columns.Command(commands =>
{
commands.Edit().ButtonType(GridButtonType.Text);
commands.Delete().ButtonType(GridButtonType.Text);
}).Width(200).Title("Command");
columns.Bound(m => m.resexpid).ClientTemplate("<a onclick='viewDetails('" + "'<#= Id #>'" + "');' href='javascript:'>View</a>").Title("View");
//columns.Bound(m => m.Date).Width(200);
})
.ClientEvents(events => events.OnRowSelect("onRowSelected"))
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Select("_FirstLook","Editresume")
.Update("_SaveAjaxEditing", "Editresume")
.Delete("_DeleteAjaxEditing", "Editresume");
})
.Scrollable(scrolling => scrolling.Enabled((bool)ViewData["scrolling"]))
.Sortable(sorting => sorting.Enabled((bool)ViewData["sorting"]))
.Pageable(paging => paging.Enabled((bool)ViewData["paging"]))
.Filterable(filtering => filtering.Enabled((bool)ViewData["filtering"]))
.Groupable(grouping => grouping.Enabled((bool)ViewData["grouping"]))
.Footer((bool)ViewData["showFooter"])
.RowAction(row => row.Selected = row.DataItem.resexpid.Equals(ViewData["id"]))
%>
<button class="button medium gray" onclick="openWindow()">Checkout</button>
<% Html.Telerik().Window()
.Name("Window")
.Title("Update Option")
.Draggable(false)
.Resizable(resizing => resizing
.Enabled(true)
.MinHeight(250)
.MinWidth(250)
.MaxHeight(500)
.MaxWidth(500)
)
.Scrollable(true)
.Modal(true)
.Buttons(b => b.Maximize().Close())
.Content(() =>
{%>
<div>
<%-- <% %>
<% if (ResumePackgeExits == true && JobPackageExist == true)
{
}
else if (ResumePackgeExits == false && JobPackageExist == true)
{
%>--%>
<div>
<table border="1" cellpadding="5" cellspacing="0" bordercolor="#CCCCCC" style="font-family:Verdana, Arial, Helvetica, sans-serif;font-size:11px;border:1px solid #AAA;margin:5px;">
<tr> <td colspan="3">
We Are also Provied a Unlimeted Resume Subscription.
if You Want a Resume Subscription Please click on RESUME Package button.
</td></tr>
</table>
<br />
<%=Html.ActionLink("RESUME Package", "ResumePackage", null, new { #class = "button medium gray" })%>
</div>
<%--<%}else if(ResumePackgeExits == true && JobPackageExist == false)
{%>
--%>
<div>
<table border="1" cellpadding="5" cellspacing="0" bordercolor="#CCCCCC" style="font-family:Verdana, Arial, Helvetica, sans-serif;font-size:11px;border:1px solid #AAA;margin:5px;">
<tr>
<td colspan="3">
We Are also Provied a Job Subscription.
if You Want a Job Subscription Please click on JOB Package button.
</td>
</tr>
</table>
<br />
<%=Html.ActionLink("JOB Package", "jobpackage", null, new { #class = "button medium gray" })%>
</div>
<%-- <%} %>--%>
<br />
<%-- <% using (Html.BeginForm("Checkout", "Package", FormMethod.Post, new { name = "frmDCC", onsubmit = "return CheckForm();" }))
{ %>
<input type="hidden" value="<%= Model.Total%>" name="totalPayment" />
<table>
<tr>
<td><%=Html.RadioButton("paymentoption","paypalPayment") %></td>
<td><img src='https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif' border='0' align='top' alt='Check out with PayPal' /></td>
</tr>
<tr>
<td><%=Html.RadioButton("paymentoption","CreditCart") %></td>
<td> <img src="https://www.paypal.com/en_US/i/bnr/horizontal_solution_PPeCheck.gif" border="0" alt="Check out with Credit Cart" /></td>
</tr>
</table>
<input type="submit" value="Go" name="submit" class="button medium gray" />
<%} %>
--%>
</div>
<%})
.Width(500)
.Height(400)
.Visible(false)
.Render();
%>
</asp:Content>
controller
public ActionResult trial()
{
//var re = (from j in db.Resumes
// select new
// Jobresults { JobTitle = j.JobTitle, Company = j.CompanyInfo }).AsEnumerable();
var re = (from j in db.Resumes join res in db.Res_Exp on j.ResumeID equals res.Resume.ResumeID
where j.ResumeID == 258
select new workexperience {title=j.ResumeTitle,company=j.DesiredCompany ,resexpid=res.ResExpID}
).AsEnumerable();
ViewData["ajax"] = true;
ViewData["scrolling"] = true;
ViewData["paging"] = true;
ViewData["filtering"] = true;
ViewData["grouping"] = true;
ViewData["sorting"] = true;
ViewData["showFooter"] = true;
return View(re);
}
In order to make customized popup in telerik grid you need to exploit editor templates. You will make an editor template for your viewmodel. this brad wilson's tutorial will help you to get start. this post at telerik forum may also help you also

ASP.NET MVC: How to call javascript function in Html.ActionLink

When I edit single recored in page, I use checkbox to get a selected row not every row with an actionlink element, but it seemed I cant make this way happen through calling javascript code (function GetSelectedRow() should return an id). Could anyone have a nice idea?
<head runat="server">
<title>Index</title>
<script type="text/javascript" language="javascript">
function GetSelectedRow() {
var a = 0;
var chkBoxes = document.getElementsByName("chkSelect");
var count = chkBoxes.length;
for (var i = 0; i < count; i++) {
if (chkBoxes[i].checked == true)
a = chkBoxes[i].primaryKeyID;
}
return a;
}
</script>
</head>
<body>
<div>
<span style="width:20%">
<%: Html.ActionLink("Add", "Create")%>
</span>
<span>
<%: Html.ActionLink("Edit", "Edit", new { id = GetSelectedRow()) %>
</span>
<span>
<%: Html.ActionLink("Detial", "Details", new { id = GetSelectedRow() })%>
</span>
<span>
<%: Html.ActionLink("Delete", "Delete", new { id = GetSelectedRow()) %>
</span>
</div>
<table>
<tr>
<th></th>
<th>
CategoryID
</th>
<th>
CategoryName
</th>
<th>
Description
</th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%: Html.ActionLink("Details", "Details", new { id = item.AppCategoryID })%>
</td>
<td>
<%: Html.CheckBox("chkSelect", false, new { primaryKeyID = item.AppCategoryID })%>
</td>
<td>
<%: item.AppCategoryID %>
</td>
<td>
<%: item.AppCategoryName %>
</td>
<td>
<%: item.Description %>
</td>
</tr>
<% } %>
</table>
</body>
You could do something like this:
<script type="text/javascript">
function RedirectUsingSelectedRow() {
var id = GetSelectedRow();
window.location = '../Controller/Details/' + id;
}
</script>
Edit
Mixing server and client that way won't work. What you need to do, when a row is selected, is to manipulate the URL. So rather than return a URL, have GetSelectedRow do:
function GetSelectedRow() {
//existing logic minus return
var link1 = document.getElementById("Link1"); //this would require giving links an ID
link1.href = '<%= Url.Action("Detail", new { controller = "Details" }) %>' +
'id=' a.toString();
}
You have to change it from client-side javascript is the key, rather than doing that during the rendering process.
HTH.
Try this -
$('#GetSelectedRow').click(function() { /* Your Code */ });
Calling java script function by id 'GetSelectedRow'. Instead of calling the function by id, you can directly call the function
<% Html.ActionLink("Edit", "Edit", "Controller", new { onclick = "GetSelectedRow();"}) %>

How to change this code in to $.ajax so that I can display message after saving to the database?

I am using this ccode right now..
<%using (Html.BeginForm("SaveNewServiceTypeCategory","ServiceTypeCategory")){ %>
<table>
<tr>
<td>Service type category:</td>
<td style="padding-left:5px;">
<input type="text" id="txtNewServiceTypeCategory" name="txtNewServiceTypeCategory" style="width:400px;" maxlength="30" />
</td>
</tr>
<tr>
<td valign="top">Service type description:</td>
<td style="padding-left:5px;">
<textarea id="txtNewServiceTypeCategoryDesc" name="txtNewServiceTypeCategoryDesc" style="width:400px;" rows="3"></textarea>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save"/>
</td>
</tr>
</table>
<%} %>
But I need to display the Popup message when data added to the Database..
I wrote somethign like this
$(function () {
$('#form1').submit(function () {
$.ajax({
url: , how to give the URl here?
type: this.method,
data: $(this).serialize(),
success: function () {
alert("Saved Successfully!");
}
});
return false;
});
After saving need to display saved Successfully message to the User?
thanks
});
You could start by giving your form an unique id:
<% using (Html.BeginForm(
"SaveNewServiceTypeCategory",
"ServiceTypeCategory",
FormMethod.Post,
new { id = "form1" })) { %>
And then use this id to register for the submit event:
$(function () {
$('#form1').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert('Saved Successfully!');
}
});
return false;
});
});
There's also the jquery form plugin which allows you to AJAXify an existing form very easily:
$(function () {
$('#form1').ajaxForm(function() {
alert('Saved Successfully!');
});
});

Resources