Ajax.BeginForm, Loading partial view help - c#

I have a project that I am working on, it's being developed in ASP.NET MVC2
Currently I have used Ajax to load some data. It works great on firefox and chrome however I have an issue with IE.
My controller:
public ActionResult UpdateSearchResults(FormCollection formValues)
{
var equipmentsResults = EquipmentQueries.GetEquipments(Request.Form["Voltage"],
Request.Form["EquipmentType"],
Request.Form["Word"]);
return PartialView("SearchResults", equipmentsResults);
}
My view:
<% using (Ajax.BeginForm("UpdateSearchResults",
new AjaxOptions {UpdateTargetId = "loadingData",
LoadingElementId = "loadingImage",
HttpMethod = "POST"}))
{ %>
<fieldset>
<legend>Filters</legend>
<label>Voltage: </label>
<%=Html.DropDownList("Voltage", (SelectList)ViewData["Voltage"], "Select Voltage", new { onchange = "this.form.submit();" })%>
<br />
<label>Equipment Type: </label>
<%=Html.DropDownList("EquipmentType", (SelectList)ViewData["Equipment"], "Select Equipment Type")%>
<br />
<label>Station Keyword Search: </label>
<%=Html.TextBox("Word")%>
<br />
<input id="btnSubmit" type="submit" value="Submit" name="submit" />
<br />
</fieldset>
<img id="loadingImage" src="../../Images/ajax-loader.gif" alt="loading"/>
<div id="loadingData"></div>
<% }%>
I have included the following scripts
<script src="../../Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
What I found during debugging is that in chrome and firefox all the DropDownList populate the Request.Form ( Request.Form("Voltage") actually displays what the user has picked on the DropDownList), however in IE this Request.Form doesn't get populated at all, it's just an empty string...
Thanks for the help everyone

While I have no clue why your code doesn't work on IE I have some suggestions about improving it. So as usual we start by defining a view model which will represent the data we are dealing with on the view:
Model:
public class ProductViewModel
{
public string SelectedVoltage { get; set; }
public IEnumerable<SelectListItem> Voltages
{
get
{
return new SelectList(new[] {
new SelectListItem { Value = "110", Text = "110V" },
new SelectListItem { Value = "220", Text = "220V" },
}, "Value", "Text");
}
}
public string SelectedEquipementType { get; set; }
public IEnumerable<SelectListItem> EquipementTypes
{
get
{
return new SelectList(new[]
{
new SelectListItem { Value = "t1", Text = "Equipement type 1" },
new SelectListItem { Value = "t2", Text = "Equipement type 2" },
}, "Value", "Text");
}
}
public string Word { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new ProductViewModel());
}
[HttpPost]
public ActionResult Search(ProductViewModel product)
{
var equipmentsResults = EquipmentQueries.GetEquipments(product);
return View(equipmentsResults);
}
}
View:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<AppName.Models.ProductViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://github.com/malsup/form/raw/master/jquery.form.js"></script>
<!-- TODO: Put this in an external javascript file -->
<!-- I've left it here just to illustrate -->
<script type="text/javascript">
$(function () {
var options = {
success: function (result) {
$('#loadingData').html(result);
}
};
$('form').ajaxForm(options);
$('#SelectedVoltage').change(function () {
$('form').ajaxSubmit(options);
});
});
</script>
<% using (Html.BeginForm("search", "home")) { %>
<fieldset>
<legend>Filters</legend>
<label for="SelectedVoltage">Voltage: </label>
<%= Html.DropDownListFor(x => x.SelectedVoltage, Model.Voltages, "Select Voltage")%>
<br />
<label for="SelectedEquipementType">Equipment Type: </label>
<%= Html.DropDownListFor(x => x.SelectedEquipementType, Model.EquipementTypes, "Select Equipment Type")%>
<br />
<label for="Word">Station Keyword Search: </label>
<%= Html.TextBoxFor(x => x.Word)%>
<br />
<input id="btnSubmit" type="submit" value="Submit" name="submit" />
</fieldset>
<% } %>
<br />
<div id="loadingData"></div>
</asp:Content>
Now you can safely dump all the MSAjax* scripts as well as all Ajax.* helpers. Do it the proper way: unobtrusively, the jquery way.

How does the generated html look like for the select elements? Check if the select contains the 'name' attribute.
such as

Related

WebForms keeps showing Event validation error on post

When I try to submit information from client to server, I receive Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/>. I've tried most of the suggestions in the answers and they don't seem to be helping.
At the top of the .aspx page in question, adding EnableEventValidation="false" does solve the issue. However, I would like to this to remain as set to true.
I've also added (!Page.IsPostBack) in the code behind and this is still causing issues.
Could it be the jQuery timpicker that's causing the issue by inputting values based on what the user selects?
Code behind .cs
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var DbHelper = new DbHelper();
listOfUsers.DataSource = DbHelper.UserList();
listOfUsers.DataBind();
}
else
{
string test = listOfUsers.SelectedValue;
string time = timePicker.Text;
string reason = ReasonForRemoval.Text;
}
}
}
.aspx file
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="xxxMyProjectNamexxx" EnableEventValidation="true"%>
<%--<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>--%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js' type='text/javascript'></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript" src="/Scripts/jquery-ui-timepicker-addon.js"></script>
<link rel="stylesheet" href="/Styles/jquery-ui-timepicker-addon.css">
<script type="text/javascript">
jQuery(document).ready(function ($) {
$('[id*=timePicker]').timepicker({
timeFormat: "hh:mm:ss"
});
});
</script>
<head>
<h2>
My App
</h2>
<p>
Enter relevant info
</p>
</head>
<body>
<form method="post">
<div>
<label for="UserName">User Name:</label>
<asp:DropDownList ID="listOfUsers" runat="server"></asp:DropDownList>
</div>
<br/><br/>
<table>
<tr>
<th>
<div>
<label for="Time">Time:</label>
<asp:TextBox ID="timePicker" runat="server"></asp:TextBox>
</div>
</th>
</tr>
</table>
<br/><br/>
<div>
<label for="Reason">Reaso:</label>
<br/>
<asp:TextBox ID="ReasonForRemoval" runat="server" TextMode="MultiLine" Rows="5" Width="400px" style="resize:none"></asp:TextBox>
</div>
<br/><br/>
<div>
<label> </label>
<input type="submit" value="Submit" class="submit" />
</div>
</form>
</body>
</asp:Content>
DbHelper.cs used to generate list
public class DbHelper
{
private EntityConnection entCon;
public DbHelper()
{
entCon = new EntityConnection(ConfigurationManager.ConnectionStrings["myConnString"].ConnectionString);
}
public List<string> UserList()
{
List<string> userList = new List<string>();
using(SqlConnection conn = (SqlConnection)entCon.StoreConnection)
using (SqlCommand cmd = new SqlCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [MyDatabase].[dbo].[users]";
using (SqlDataReader objReader = cmd.ExecuteReader())
{
if (objReader.HasRows)
{
while (objReader.Read())
{
userList.Add(Convert.ToString(objReader[0]));
}
}
}
}
return userList;
}
}
}

Razor: Transfer input text + Model to a controller

Hy everybody,
In my Razor View page, I have a text input. I want to call a controller by using the "onchange" event and add my input value to a list contained in my Razor Model.
This is my html page:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>MyForms</title>
</head>
<body>
<label>Code</label>
<form method="post" action="">
<input name="NPItem" maxlength="11" autofocus onkeypress="return isNumberKey(event)" onchange="location.href = '#Url.Action("addtoList", "MyController", new { formsData = Newtonsoft.Json.JsonConvert.SerializeObject(Model) })';"/>
</form>
<table border="1" id="listeNPAI">
<tr>
<th>Index</th>
<th>Value</th>
</tr>
#{
foreach (Tuple<string, string> item in Model.list) {
<tr>
<td>#item.Item1</td>
<td>#item.Item2</td>
</tr>
}
}
</table>
</body>
</html>
This is my called controller action :
public ActionResult addtoList(string formsData) {
formsData _form = Newtonsoft.Json.JsonConvert.DeserializeObject<ModelClass>(formsData);
string input = Request["NPItem"];
if (input == null) { input = ""; } else { input = input.Trim(); }
if (input.Length == 11) {
_form.list.Add(new Tuple<string, string>(input.Substring(0, 5), input.Substring(6)));
}
return View("FormulaireNPAI", _form);
}
I add the input text value to the list in my controller action. The problem is that input is always '==null' (because there is no submit). However, it works when I press the Enter keyboard button.
Help, please
Thks in advance
You could do something like this:
$("#element").on("click", function() {
$.ajax({
url: "action",
type: "GET",
data: { data }
})
.done(function(partialViewResult) {
$("#yourViewWrapper").html(partialViewResult);
});
});
i.e. made AJAX call when you need and then refresh your view.

Razor Jquery UI datepicker not working

I've read a lot of the questions on stackoverflow about this, tried some examples and am still stuck why this won't work. So I am asking the community.
MODEL:
public class UploadModel
{
public string PatientID { get; set; }
public DateTime DrawDate { get; set; }
}
Controller:
public class FileManagementController : Controller
{
[HttpGet]
public ActionResult UpLoad()
{
ViewData["message"] = String.Empty;
UploadModel model = new UploadModel
{
PatientID = String.Empty,
DrawDate = DateTime.Now,
};
return View(model);
}
[HttpPost]
public ActionResult Upload(UploadModel model, HttpPostedFileBase MyFile)
{
if (ModelState.IsValid)
{
//Do Validation and Save here
}
UploadModel newmodel = new UploadModel
{
PatientID = model.PatientID,
DrawDate = model.DrawDate,
};
ViewData["message"] = "data submitted";
return View(newmodel);
}
View:
<form action="" method="post" enctype="multipart/form-data" id="MyForm">
#Html.EditorFor(m => m)
<label for="MyDateTime">My Date Time:</label>
<label for="MyFile">File:</label>
<input type="file" name="MyFile" id="MyFile" /><br />
<input id="submit" name="submit" type="submit" value="Save" />
</form>
From there, I have added to the _Layout.cshtml page the following code (which all maps correctly)
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/jquery-ui-1.7.2.custom.css")" rel="stylesheet" type="text/css" />
<script src='#Href("~/Scripts/jquery-1.7.1.js")' type="text/javascript" ></script>
<script src='#Href("~/Scripts/jquery-ui-1.8.1.custom.min.js")' type="text/javascript" ></script>
<script type="text/javascript" src='#Href("~/Scripts/jquery.alphanumeric.pack.js")'></script>
<script type="text/javascript" src='#Href("~/Scripts/jquery.watermark.min.js")'></script>
Then in Views -> Shared I have added an EditorTemplates folder and have created a DateTime.cshtml page that has:
#model DateTime
#Html.TextBox("", Model.ToString("dd/MM/yyyy"),
new { #class = "date" })
<script type="text/javascript" >
$(document).ready(function () {
//set the date picker
var dtp = '#ViewData.TemplateInfo.GetFullHtmlFieldId("")';
dtp = dtp.replace("[", "_");
dtp = dtp.replace("]", "_");
//window.alert($(dtp).attr("value"));
var hid = ($(dtp).attr("type") == "hidden");
if (!hid) {
$(dtp).datepicker({
showOn: 'button', buttonImage: '#Href("~/Content/images/calendar.gif")%>', buttonImageOnly: true
, changeMonth: true, changeYear: true
, dateFormat: 'dd M yy'//, numberOfMonths: 2
});
}
});
</script>
This seems to be the flavor of most of the tutorials on this, but don't seem to work. No icon appears. In Chrome I get the html5 calendar popup but never the jquery one. Any suggestions at all would be greatly appreciated.
The selector looks incorrect to me. You're code:
var dtp = '#ViewData.TemplateInfo.GetFullHtmlFieldId("")';
Would result in a string: 'my_id', but you still need to tell jQuery that string is an ID, using the # symbol like so:
var dtp = '##ViewData.TemplateInfo.GetFullHtmlFieldId("")';
As a side note, do you really want to export that entire Script tag for each rendered DateTime in your model? Seems unnecessary to me, but you may have already thought about this. My recommendation would be to modify your DateTime.cshtml to simply:
#model DateTime
#Html.TextBox("", Model.ToString("dd/MM/yyyy"), new { #class = "date-picker" })
Then somewhere in your page or Layout, something like:
<script type="text/javascript" >
$(function () {
$('.date-picker').datepicker({
showOn: 'button', buttonImage: '#Href("~/Content/images/calendar.gif")%>', buttonImageOnly: true
, changeMonth: true, changeYear: true
, dateFormat: 'dd M yy'//, numberOfMonths: 2
});
});
</script>
That way, just one script is rendered and all your DateTime's are taken care of.
Since I'm a noob I can't post a comment (sorry!), but the only advice I can give is to make sure that the html derived from #Html.EditorFor(m => m) is exactly what you need (this html is different depending on the model). Here's more info about that: http://msdn.microsoft.com/en-us/library/ee402949(v=vs.98).aspx
Also, I noticed in the javascript section you have a %> at the end here: "#Href("~/Content/images/calendar.gif")%>" and it looks like an error.

ASP.NET MVC 2 View with PartialView - PartialView Opens New Page

My code works perfectly in VS2010 C# but once published to IIS7 the PartialView (list of records) does not get rendered in the View...it rolls to a new page without the data except for the correct record count retrieved from SQL server. SQL server is on separate box.
I have searched for hours on this site with no luck finding a resolution.
View with the RenderPartial:
<table style="width:100%">
<tr>
<td>
<h3>Outage Tracking List (Open or Active)</h3>
</td>
<td style="text-align:right">
<h1><%: ViewData["ApplicationName"]%></h1>
</td>
</tr>
</table>
<% Html.RenderPartial("OutageSearch",this.ViewData.Model); %>
PartialView:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl&ltOutageTrackingWebSite.Models.OutageViewModel" %>
<div>
<script language="javascript" type="text/javascript">
function OutageSearch() {
$("#OutageSearchForm #CurrentPageNumber").val("1");
PostSearchForm();
}
Various functions then the rest of the partialview
<% using (Ajax.BeginForm("OutageSearch", null,
new AjaxOptions { UpdateTargetId = "DivOutageSearchResults", OnComplete="OutageSearchComplete" },
new { id = "OutageSearchForm" })) { %>
<table style="background-color: #ebeff2; width: 100%; border:solid 1px #9fb8e9" cellspacing="2" cellpadding="2">
<tr>
<td style="width: 60%; text-align: left">
<input id="btnSearch" onclick="OutageSearch();" type="submit" value="List Open/Active" />
</td>
</tr>
</table>
<div id="DivOutageSearchResults">
<% Html.RenderPartial("OutageSearchResults", this.ViewData.Model); %>
</div>
<% } %>
additional PartialView
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<%OutageTrackingWebSite.Models.OutageViewModel" >
<input name="CurrentPageNumber" type="hidden" id="CurrentPageNumber" value="<%=Model.CurrentPageNumber%>" />
<input name="TotalPages" type="hidden" id="TotalPages" value="<%=Model.TotalPages%>" />
<input name="SortBy" type="hidden" id="SortBy" value="<%=Model.SortBy%>" />
<input name="SortAscendingDescending" type="hidden" id="SortAscendingDescending" value="<%=Model.SortAscendingDescending%>" />
<input name="PageSize" type="hidden" id="PageSize" value="9" />
<script language="javascript" type="text/javascript">
function GetOutageDetails(OutageID) {
if (formIsDisabled == false) {
DisableForm();
formData = "OutageID=" + OutageID;
setTimeout(PostOutageIDToServer, 1000);
}
}
function PostOutageIDToServer() {
$.post("/Outage/GetOutageInformation", formData, function (data, textStatus) {
OutageUpdateComplete(data);
}, "json");
}
Controller
public ActionResult DisplayOutageList()
{
Models.OutageViewModel outageViewModel = new Models.OutageViewModel();
outageViewModel.TotalPages = 0;
outageViewModel.TotalRows = 0;
outageViewModel.CurrentPageNumber = 0;
ViewData.Model = outageViewModel;
string applicationName = Convert.ToString( System.Configuration.ConfigurationManager.AppSettings["ApplicationName"]);
ViewData["ApplicationName"] = applicationName;
return View("OutageMaintenance");
}
///
/// Outage Search
///
///
public PartialViewResult OutageSearch()
{
long totalRows;
long totalPages;
bool returnStatus;
string returnErrorMessage;
OutageBLL OutageBLL = new OutageBLL();
Models.OutageViewModel outageViewModel = new Models.OutageViewModel();
this.UpdateModel(outageViewModel);
List Outages = OutageBLL.OutageSearch(
outageViewModel,
outageViewModel.CurrentPageNumber,
outageViewModel.PageSize,
outageViewModel.SortBy,
outageViewModel.SortAscendingDescending,
out totalRows,
out totalPages,
out returnStatus,
out returnErrorMessage);
ViewData["Outages"] = Outages;
outageViewModel.TotalPages = totalPages;
outageViewModel.TotalRows = totalRows;
ViewData.Model = outageViewModel;
return PartialView("OutageSearchResults");
}
///
/// Get Outage Information
///
///
public JsonResult GetOutageInformation()
{
bool returnStatus;
string returnErrorMessage;
List returnMessage;
OutageBLL outageBLL = new OutageBLL();
Models.OutageViewModel outageViewModel = new Models.OutageViewModel();
this.TryUpdateModel(outageViewModel);
Outage outage = outageBLL.GetOutageInformation(
outageViewModel.OutageID,
out returnStatus,
out returnErrorMessage,
out returnMessage);
outageViewModel.UpdateViewModel(outage, typeof(Outage).GetProperties());
outageViewModel.ReturnMessage = returnMessage;
outageViewModel.ReturnStatus = returnStatus;
outageViewModel.OutageScheduledDate = UtilitiesBLL.FormatDate(outageViewModel.ScheduledDate);
outageViewModel.OutagePlannedDuration = UtilitiesBLL.FormatDuration(outageViewModel.PlannedDuration);
return Json(outageViewModel);
}
Check your included JavaScript files on the deployed version. If you are missing some files (MicrosoftMvcAjax.js, jQuery.js), the page could simply be posting instead of using an Ajax post.

call jquery script after file upload finished asp.net mvc 2

i am trying to display a jquery popup after a fileupload action? not sure how to code this?
<%= Html.BeginForm("Upload","Home",FormMethod.Post,new { enctype = "multipart/form-data" }) %>
<%{ %>
<input type="file" id="upload" name="upload" />
<button id="btnUpload">
upload</button>
<%} %>
<script type="text/javascript">
function SayFinished() {
alert('Finished');
}
</script>
[HttpPost]
public ActionResult Upload()
{
HttpPostedFileBase selectedFile = Request.Files["upload"];
if (selectedFile.ContentLength > 0 )
{
//do some processing call jquery script to open popup: SayFinished()
}
return View("Index");
}
The simplest way to do this is to return a view from your controller after the post that has an onload script.
On the new view, put the following javascript:
In the controller set the following after file uploaded
ViewData["FileUploaded"] = "true";
Then in the view set
<% if (!String.IsnullOrEmpty(ViewData["FileUploaded"]) && ViewData["FileUploaded"] == "true") { %>
<script type="text/javascript">
$(document).ready(function() {
SayFinished();
});
function SayFinished() {
alert('Finished');
}
</script>
<%} %>
You can use this plugins to upload file using jQuery, http://pixelcone.com/jquery/ajax-file-upload-script
Sorry for previous feedback with incorrect information.

Categories

Resources