In MVC 4, I have a textbox with Autocomplete functionality in a partial view And i am using this partial view in two views,view 1 and View 2.In View 1 ,it is working fine, as view 1 does not have any postback, while in View 2, i have a submit button causing postback,and after this postback,the partial is shown on the screen or else it is hidden.The Autocomplete here is not working.
$("#txtProduct").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
data: { term: request.term },
datatype: JSON,
url: 'UploadEligibilityCodes/GetAllMatchingProducts',
success: function (data) {
response($.map(data, function (value, key) {
return {
label: value.ProductName.concat("(", value.ProductId, ")"),
value: value.ProductName,
pid: value.ProductId
};
}))
}
});
},
select: function (event, ui) {
$('#hdnProductIdSearch').val(ui.item.pid);
}
});
This is the code of my text box defined in Partial view named SearchFilters.cshtml and View 2 which uses this partial view as follows.
#using (Html.BeginForm( "Validate","UploadEligibilityCodes",FormMethod.Post, new {id="UploadForm" , enctype = "multipart/form-data" }))
{
<div class="col-sm-1 form-group">
<button type="submit" class="SIMPLDocumentUploadSave" id="importbtn" value="Import" style="width: 100px"> Import</button>
</div>
}
<div class="col-sm-12 form-group SIMPLAdvancedFilterOptions">
#Html.Partial("SearchFilters")
</div>
I saw some examples using Sys.WebForms.PageRequestManager in ASP.Net, but the same i am not able to apply it html of mvc application.Please help :)
Can you replace your submit button with regular one and call submit() on form manually with jQuery? This can help you with postback issue
Related
Thanks in advance.
I am working on a product filter view similar to some thing like on amazon. where I have refresh multiple views but the data for all the partial view come from single ajax call how to refresh multiple partial view. I can refresh main content area completely but some partial views are not supposed to be refreshed.
I broke it down into steps so you can follow/modify and add your partials like here. First, add 3 Partial Views, they have the same code like below,
#model int
<div class="container fluid">
<h1>PartialDemo#(Model)</h1>
<h3>The views will all update when you click update button below</h3>
</div>
DashboardWidgets.cshtml, the code like below, whatever your csthml page is
//<div class="row-fluid">
// <div class="col">
<div id="WidgetID_1" class="container">
#Html.Partial("_PartialWidget1", 1)
</div>
<div id="WidgetID_2" class="container">
#Html.Partial("_PartialWidget2", 2)
</div>
<div id="WidgetID_3" class="container">
#Html.Partial("_PartialWidget3", 3)
</div>
<div id="WidgetID_4" class="container">
#Html.Partial("_PartialWidget3", 4)
</div>
//</div> // the col
//</div> // the row
// lcik below button to update the partials above
// ***** One button will update them all like you wanted
<button type="button" onclick="UpdateMyWidgets()" class="btn btn-primary">Update All Partial View Views</button>
#section scripts{
<script type="text/javascript">
// this one button will update all your partials/widgets, you can add more partials in this function and just copy paste.
function UpdateMyWidgets() {
$.ajax({
url: "#Url.Action("Widget1")", // whom to call
type: "POST",
datatype: "HTML",
success: function (data) {
$("#WidgetID_1").html(data); // tell it which div to append on return
}
})
$.ajax({
url: "#Url.Action("Widget2")",
type: "POST",
datatype: "HTML",
success: function (data) {
$("#WidgetID_2").html(data);
}
});
$.ajax({
url: "#Url.Action("Widget3")",
type: "POST",
datatype: "HTML",
success: function (data) {
$("#WidgetID_3").html(data);
}
});
}
</script>
}
When click the "Update All Partial View Views" button, it will call "Update" method. If success, the return data will replace div's content
Backend action ajax request.
// these actions get called from the Update Buttons
public ActionResult Widget1()
{
return PartialView("_PartialWidget1", 11);
}
public ActionResult Widget2()
{
return PartialView("_PartialWidget2", 21);
}
public ActionResult Widget3()
{
return PartialView("_PartialWidget3", 31);
}
I have a html form in which I write in a text box and submit when press a button and it saves in db but I want the page not to refresh and continue with the values in the text box
I have see people talking about ajax but I have never worked with ajax
<div class="row" style="float:left; margin: 2px ">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="col-md-3">
<div class="form-group">
<label>Pressão Injeção:</label>
<input id="id3" type="text" name="Pressão_de_Injeção" /> <br />
</div>
</div>
Here is a quick example of an AJAX call which will POST data to an controller:
var menuId = $("ul.nav").first().attr("id");
var request = $.ajax({
url: "Home/SaveForm",
type: "POST",
data: {id : menuId},
dataType: "html"
});
request.done(function(msg) {
console.log('success');
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Note, that you can also pass objects to the controller by supplying them as an variable within the data object:
var menuId = $("ul.nav").first().attr("id");
var obj = {
id: menuId,
text: "Foo"
};
var request = $.ajax({
url: "Home/SaveForm",
type: "POST",
data: {name: "Jim", object: Obj},
dataType: "html"
});
(Code adapted from an answer by apis17.)
An introduction to AJAX, can be found here:
https://www.w3schools.com/js/js_ajax_intro.asp
The only other method of performing what you required (without using AJAX) is to use a form submit and pass the data back to the HTML form once complete. You would then need to re-populate the fields (however, this will cause additional work on both submitting and re-populating, if (and/or when) new fields are adding if the future).
You will have to take the ajax approach.
But if you don't want to do that, you can always post to the controller and return the model to the view. It will have the text you entered into the textbox.eg.
public IActionResult MyView()
{
return View();
}
[HttpPost]
public IActionResult MyView(MyModel model)
{
return View(model);
}
Hope this helps as an alternative.
I have a webpage where many section of the page gets loaded using jQueryAjax after intial load. Now I need to download the web page completey using C#. It should be downloaded once all the ajax call completes.
I tried many ways to do that but didnot get through. Can sombody suggest the best way to handle that?
I have my MVC view like this
#{
ViewBag.Title = "My Page";
}
<div id="Banner" class="divMain" style="height: 92px;" style="margin-left: 0.3em">
</div>
<div style="float:left; width:99.6%">
<div id="StockPriceCharts" class="div_Chart" style="margin-top:0.1em;margin-left:-0.1em">
</div>
<div id="Rating" class="divMain_48" style="margin-left: 0.3em; min-height:140px">
<div class="ControlHeader">
Entity Details</div>
<div id="dvEntity" >
</div>
</div>
<div id="FilMeetings" class="divMain_48" style="float:left;">
<div class="ControlHeader">
MEETINGS
</div>
<div id="dvMeeting" style="height: 119px;" class="loading">
</div>
</div>
</div>
<span>
<input id="IdHidden" type="hidden" value="#ViewBag.SymbolId"/>
</span>
<script type="text/javascript">
$.ajaxSetup({ cache: false });
// For Entity Detail
$.ajax({
url: '/HomePage/Entity Detail/' + $('#IdHidden').val(),
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { symbolId: document.getElementById("IdHidden").value }
})
.success(function (result) {
$('#dvEntity').html(result);
})
.error(function (xhr, status) {
$('#dvEntity').html('<div style="height:40px;" class="loading">Failed to load Entities</div>');
});
$.ajax({
url: '/HomePage/GetMEETINGSs/' + $('#IdHidden').val(),
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { symbolId: document.getElementById("IdHidden").value }
})
.success(function (result) {
$('#dvMeeting').html(result);
})
.error(function (xhr, status) {
$('#dvMeeting').html('<div style="height:40px;" class="loading">Failed to load Business description</div>');
});
</script>
I have removed some part and put dummy value for brevity. But I have similar more section that are getting loaded via AJAX and there are some static content as well. When I download it ajax section is not getting loaded.
If I understand you right, after page loaded you're loading data with ajax and rendering it with JavaScript.
If so, you have to implement data rendering in Razor way (If you're using ASP.NET MVC). Each section should have own partial view. Create a new View and put Partials in it.
public ViewResult Index()
{
var api = new YouWebApiController();
var sectionData_1 = api.GetSectionData_1();
var sectionData_2 = api.GetSectionData_2();
var sectionData_3 = api.GetSectionData_3();
ViewBag.SectionData_1 = sectionData_1;
ViewBag.SectionData_2 = sectionData_2;
ViewBag.SectionData_3 = sectionData_3;
return new View();
}
In your view:
<body>
#Html.RenderPartial("SectionPartial_1", ViewBag.SectionData_1);
#Html.RenderPartial("SectionPartial_2", ViewBag.SectionData_2);
#Html.RenderPartial("SectionPartial_3", ViewBag.SectionData_3);
</body>
I've been trying to add some Ajax functionality to my mvc site, however, I run into a problem regarding page refreshing. I've created an rss view on my homepage sidebar, which allows the user to select which rss feed they want to view using a drop down list. Initially I was using the html.begin form option in mvc, however, I decided it would be a cool feature to have the rss feeder refresh, rather than having the whole page refresh. I implemented the ajax.begin form, but the whole page is still refreshing.
Here is the code inside my view:
<div class="rss_feed">
<h3>RSS Feed</h3>
#using (Ajax.BeginForm("Index", "Home",
new AjaxOptions
{
HttpMethod = "post",
UpdateTargetId = "feedList"
}))
{
#Html.DropDownListFor(x => x.SelectedFeedOption, Model.FeedOptions)
<input type="submit" value="Submit" />
}
<div id="feedList">
#foreach (var feed in Model.Articles)
{
<div class="feed">
<h3>#feed.Title</h3>
<p>#feed.Body</p>
<p><i>Posted #DateTime.Now.Subtract(#feed.PublishDate).Hours hour ago</i></p>
</div>
}
</div>
</div>
When the user selects a feed type from the drop down menu, and clicks the submit button, the feed should update to the selected option.
In the _Layout view the following bundle is loaded:
#Scripts.Render("~/bundles/jquery")
Any help would be great.
I use an ajax call in jquery for this
$('#SelectedFeedOption').change(function() {
$.ajax({
url: "#(Url.Action("Action", "Controller"))",
type: "POST",
cache: false,
async: true,
data: { data: $('#SelectedFeedOption').val() },
success: function (result) {
$(".feedList").html(result);
}
});
});
Then put the contents of your feedList div in a partial view and on your controller
public PartialViewResult FeedList(string data){
Model model = (get search result);
return PartialView("_feedList", model);
}
Hopefully this helps.
Did you try initializing the InsertionMode member into the AjaxOptions object initializer?
You also have to include 'jquery.unobtrusive-ajax.js' to make Ajax.BeginForm to work as answered here
#using (Ajax.BeginForm("Index", "Home", null,
new AjaxOptions
{
HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "feedList"
});
{
#Html.DropDownListFor(x => x.SelectedFeedOption, Model.FeedOptions)
<input type="submit" value="Submit" />
}
I am having a problem using client side validation in combination with Data Annotations.
The project is using ASP.NET Framework 4.5, a Web Application with the MVP pattern and jQuery Ajax calls to dynamically load user controls.
This is the (stripped) user control which contains the input element that needs to be validated:
<form id="insertArtist" class="form-horizontal">
<fieldset>
<legend>Add new artist</legend>
<div class="control-group">
<label class="control-label" for="name">Name</label>
<div class="controls">
<asp:TextBox runat="server" ID="name" ClientIDMode="Static" CssClass="input-medium"></asp:TextBox>
<ml:DataAnnotationValidator runat="server" ID="davName" ControlToValidate="name" EnableClientScript="true" PropertyToValidate="Name" SourceTypeName="Music.Library.Domain.Models.Artist, Music.Library.Domain">
</ml:DataAnnotationValidator>
</div>
<div class="form-actions">
<button id="save" class="btn btn-primary" name="submit" type="submit">Save</button>
<button id="cancel" class="btn">Cancel</button>
</div>
</div>
</form>
This user control get's dynamically loaded using the following ajax call:
$('#add').click(function () {
$.ajax({
url: "/Artist/Manage/Insert.ascx.axd",
type: "POST",
dataType: "html",
success: function (obj) {
$('#body_artist').html($(obj));
}
});
});
This is the jquery executed when a user clicks save:
$('#save').click(function (event) {
event.preventDefault();
$.ajax({
url: "/artist/add.axd",
type: "POST",
dataType: "html",
cache: false,
async: true,
data: 'Ajax=true&' + $('#insertArtist').serialize(),
beforeSend: function (jqXHR, settings) {
$('#loading').show();
},
success: function (data) {
if (data == "succes") {
showNotification('succes', 'Succesfully added artist');
} else {
showNotification('error', 'Error while adding artist: ' + data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
showNotification('error', 'Error while adding artist: ' + data);
},
complete: function () {
$('#loading').hide();
}
});
});
Now, since there is no trigger from an asp.net control the custom data annotation validator will not validate.
I've tried validating using Javascript, using the Page_ClientValidate(), ValidateEnable() and Validate() methods. Unfortunately when trying this I keep getting the same error over and over:
Page_ClientValidate is not defined
Same story for the other methods.
I'm at wits end here.
Is it because the UserControl is dynamically loaded that these client validation methods do not work? I've set EnableClientScript to true.
Or does anyone have another idea on how to implement this? I'd really like to use the Data Annotations.
Thanks in advance!
It can be a solution
http://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/
Especially, it is a dublicate of this question Unobtrusive validation not working on dynamically-added partial view which also refers to XHalent blog