Ajax.BeginForm refreshing the whole page in MVC - c#

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" />
}

Related

How do I submit a form, but my text boxes preserve their values in asp.net Razor pages

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.

how to upload a file using jquery + c#

I'm having issues trying to upload a docx file. First, when I click on "Choose File", the prompt opens up but the page reloads going to CheckInController/CheckIn url ( I thought that what you add in the Html.BeginForm is where your controller and method go when you click on submit ). Second thing is how do I know that the contents of the document are being sent to the server and not just the name or id?
https://jsfiddle.net/w6adx6za/1/
<div class="session-filter">
#using (Html.BeginForm("CheckIn", "CheckInController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="select-filter-title"><strong>Select File</strong></div>
<table>
<tr>
<td><input name="fileResume" id="hiddenFileResume" type="file" value="" /><input type="submit" onclick="tested()"/></td>
</tr>
</table>
}
</div>
function tested(){
$.ajax({
cache: false,
type: "POST",
url: "/SummaryStatementProcessing/CheckInSummaryStatement",
data: data
});
}
public ActionResult CheckIn(HttpPostedFileBase fileResume){
//work in here
}
I don't need the page to go anywhere ( because this is actually in a dialog so it can close on submit, but currently it's reloading the page at the url above ). Currently I can't even get to the controller to check...
To do what you require, the easiest method is to send a FormData object in the request. However, you should ideally be hooking to the submit event of the form, not the click of the submit button, to stop the page redirecting.
You'll need to set the processData and contentType properties to false in the request. Also, the Action name does not appear to match your URL. You can fix that by using #Url.Action. The Action also needs the [HttpPost] attribute as that's the HTTP verb you're using in the AJAX request.
With all that said, try this:
<div class="session-filter">
#using (Html.BeginForm("CheckIn", "CheckInController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="select-filter-title"><strong>Select File</strong></div>
<table>
<tr>
<td>
<input name="fileResume" id="hiddenFileResume" type="file" value="" />
<input type="submit" />
</td>
</tr>
</table>
}
</div>
$('.session-filter form').submit(function(e) {
e.preventDefault();
$.ajax({
cache: false,
type: "POST",
url: '#Url.Action("CheckIn", "SummaryStatementProcessing")',
data: new FormData(this),
processData: false,
contentType: false,
});
}
[HttpPost]
public ActionResult CheckIn(HttpPostedFileBase fileResume)
{
// work in here
}
With the above code in place, you should then be able to work with the HttpPostedFileBase class in the Action.

ASP.NET MVC: Put searching attributes into url (not query string)

have implemented filtering on my ASP.NET MVC 5 app.
My searchbox consists of a few Dropdownlists with predefined values. When the Dropdownlist value changes, the form is submitted and I see all available tickets for a specific method.
After the form submits the page reloads and I see the url like mysite.com/?Method=car. But I would like to get rid of the query string and put car directly into the url, i.e.
mysite.com/method/car or mysite.com/method/plain etc
Is it possible?
Search box
#using (Html.BeginForm("Search", "Transfer", FormMethod.Get))
{
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-10">
#Html.DropDownListFor(model => model.Method, Model.Methods, new { #class = "query"})
</div>
</div>
</div>
<input type="submit" class="hidden" />
}
My action method
[Route("~/transfer/{method?}")]
public async Task<ActionResult> List(string method)
{
//filter and displaying
return View(viewModel);
}
By default Html.BeginForm with FormMethod.Get will serialize all the form values into query string. So if you want friendly URLs you will have to write some JavaScript (jQuery in this example).
First of all you can remove the form
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-10">
#Html.DropDownListFor(model => model.Method, Model.Methods, new { #class = "query"})
</div>
</div>
</div>
<button type="button" id="submitMethodBtn">Submit</button>
<script>
var baseUrl = '#Url.Action("Search", "Transfer")/'
$('#submitMethodBtn').click(function(){
var url = baseUrl + $(#'#Html.IdFor(m=>m.Method)').val();
window.location.href = url;
})
</script>
Some issues/clarifications:
1if you enter mysite.com/method/car (assuming that issue #2 is resolved )in browser it will take you to a correct action so your issue is basically generating friendly Url in the view.
2 In the provided code example i used an inline script. You can extract it to a separate static file but you will have to hard-code the url and the html id for Method property.
3 Your action method gets int as parameter so how do you expect it to work with mysite.com/method/car (car is a string) ?
You can call an ajax method on page which will avoid query string and when controller redirects to ActionResult then again you can call ajax method on redirected page. By this way you can avoid query string in MVC.
Take below code as example.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Transfer/search",
data: "{ID:1}",
dataType: "json",
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
Make return type as JsonResult of controller method.

Partial View content is not reloaded

I have a view with a button, when click this button, an ajax function calls controller method ApplicationAndUse which is supposed to pass a list to a partial view included in my view. The partial view content is supposed to be refreshed, but this doesn't work, my partial is still empty.
My code :
Main view :
#model List<String>
<div class="row">
<div class="col-md-2">
#foreach (var item in Model)
{
<div id="univers-#item" class="btn btn-info">#item</div><br />
}
</div>
<div class="col-md-10">
#Html.Partial("_ApplicationAndUsePartial", null, new ViewDataDictionary())
</div>
</div>
#section scripts
{
<script type="text/javascript">
$(function () {
$('[id^=univers]').click(function () {
var selectedButton = $(this).attr('id');
var selectedUniverse = selectedButton.substring(selectedButton.indexOf('-') + 1, selectedButton.lenght);
$.ajax({
url: "http://" + window.location.host + "/UseAndNeed/ApplicationAndUse",
type: "POST",
data: { idUniverse: selectedUniverse },
dataType: "json",
});
});
});
</script>
}
Partial view :
#model List<int>
#if (Model!= null) {
foreach (var item in Model)
{
<div id="ApplicationUse-#item" class="btn btn-default">#item</div><br />
}
}
Controller function :
[OutputCache(Duration = 0)]
public ActionResult ApplicationAndUse(String idUniverse)
{
List<int> items = new List<int>();
items.Add(1);
items.Add(2);
return PartialView("_ApplicationAndUsePartial", (object)items);
}
what do i miss?
Give a unique Id to the div where we want to show the partial view content.
<div id="myPartial" class="col-md-10">
#Html.Partial("_ApplicationAndUsePartial", null, new ViewDataDictionary())
</div>
And in the success handler of the ajax method, update this div's innerHTML with the response coming from the ajax call. Also you do not need to pass specify the dataType value when making the ajax call.
var myUrl= "http://" + window.location.host + "/UseAndNeed/ApplicationAndUse";
$.ajax({ type: "POST",
url : myUrl,
data: { idUniverse: selectedUniverse },
success:function(result){
$("myPartial").html(result);
}
});
Always you should use the Url.Action or Url.RouteUrl html helper methods to build the url to the action methods. It will take care of correctly building the url regardless of your current page/path.
var myUrl= "#Url.Action("ApplicationAndUse","UseAndNeeed")";
This works if your js code is inside the razor view. But If your code is inside a seperate javascript file, you may build the url(s) in your razor view using the above helper methods and keep that in a variable which your external js file code can access. Always make sure to use javascript namespacing when doing so to avoid possible issues with global javascript variables.
#section Scripts
{
<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.baseUrl = '#Url.Content("~")';
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>
}
And in your PageSpecificExternalJsFile.js file, you can read it like.
var myUrl= myApp.Urls.baseUrl+"UseAndNeed/ApplicationAndUse";
$("#myPartial").load(myUrl+'?idUniverse=someValue');

Jquery Autocomplete not working after postback

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

Categories

Resources