Asp.net MVC Post Data To Controller without refreshing page [duplicate] - c#

This question already has answers here:
Send post data from html FORM with Javascript?
(5 answers)
Closed 4 years ago.
I am posting a selected value from Dropdown List. but after getting my value page goes refresh. How to post data without page refresh to controller?
Here is view:
<div class="container">
<div class="row">
#foreach (var item in Model)
{
using (Html.BeginForm("AddToCart", "Test", new { id = item.ProductId }, FormMethod.Post))
{
<div class="col-md-3 col-sm-4 col-xs-6">
<img id="ImageClick" onclick="location.href='#Url.Action("ViewProductOnClick", "Home", new { id = item.ProductId })'"
src="#Url.Content("~/Content/" + item.ImageURL)" height="200" width="200" alt="#item.ProductName" />
<div class="productDetails">
<div class="productName">
<h5 id="ProductName" class="bold name">Name: #item.ProductName</h5>
</div>
<div class="productPrice bold" id="ProductPrice">
Rs. <span class="unit"> #item.Price</span>
</div>
<div class="productCart">
<div class="col-lg-6 col-md-12 col-sm-12 col-xs-12 no-padding">
<input type="submit" class="btn btn-success" id="btnSubmit" value="Add to Cart" />
</div>
</div>
</div>
</div>
}
}
</div>
</div>
Here is my controller:
[HttpPost]
public ActionResult AddToCart(int id, FormCollection collection)
{
MyDBContext myDBContext = new MyDBContext();
if (ModelState.IsValid)
{
var cartFill = myDBContext.Products.Find(id);
int quantity = Convert.ToInt16(collection["Weight"]);
AddToCart addToCart = new AddToCart(cartFill, quantity);
if (Session["cart"] == null)
{
List<AddToCart> list = new List<AddToCart>();
list.Add(addToCart);
Session["cart"] = list;
}
else
{
List<AddToCart> list = (List<AddToCart>)Session["cart"];
list.Add(addToCart);
Session["cart"] = list;
}
}
return RedirectToAction("ViewCart", "Home");
}

You can do it like this;
1) You have to create partial view for your action (Action is you want to post)
2) Add Reference of jquery.unobtrusive-ajax.
Using NuGet package manager, you can install library and reference into the project.
here is the package link https://www.nuget.org/packages/Microsoft.jQuery.Unobtrusive.Ajax/
3)To work Ajax.BeginForm functionality properly don't forget to add the reference into page
After you do these, you can post data to controller without Page refresh in ASP.NET MVC using Ajax.BeginForm.
For detailed explanation you can read this link:
post-data-without-whole-postback

You should use a partial view if you want to update only portions of the page instead of refreshing it.
Here is a useful link to start with: http://www.tutorialsteacher.com/mvc/partial-view-in-asp.net-mvc.

Related

Pass a list from get method (or from a view) to post method ASP .NET MVC

I apologize if the heading is not very clear.
So, what I want to do is following.
I have a model class called "Class" that contains a list of "Students". I have a view that shows a checklist of Students. From that checklist I want to pass the selected students back to controller, where I will update the Database and my class will have new students and the added students will have a new class.
Here is what I have done so far but now I am stuck. Thanks in advance.
These are my controller actions
[HttpGet]
public ActionResult AddStudents(int? id)
{
List<Student> students = (from std in db.Students
where std.St_cl_fk_id == null select std).ToList();
//ViewBag.students = students;
return View("Add_Students",students);
}
[HttpPost, ActionName("AddStudents")]
public ActionResult AddStudentsPost(int? id,List<Student> students)
{
if(ModelState.IsValid)
{
var temp = id;
Class #class = db.Classes.Find(id);
foreach (var item in students)
{
if (Request.Form[item.St_id.ToString()] != null)
{
#class.Students.Add(item);
}
}
db.Entry(#class).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index", "Classes");
}
return View("Add_Student");
}
Here is my view
#model IEnumerable<GMASchoolProject.Models.Student>
#{
ViewBag.Title = "Add_Students";
}
<h4>Student List</h4>
#using (Html.BeginForm())
{
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
Check Students
</div>
<div class="form-group">
<div class="col-md-10">
<table>
#foreach (var std in Model)
{
<tr>
<td><input type="checkbox" name="#std.St_id" value="#std.IsSelected" /></td>
<td>#Html.Label((string)std.St_name)</td>
</tr>
}
</table>
</div>
</div>
<div class="form-group" style="margin:15px,0,15px,0;">
<div class="col-md-offset-5 col-md-2">
<input type="submit" value="Add Students" class="btn btn-primary" />
</div>
</div>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index", null, new { #class = "btn btn-danger" })
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Please let me know if there is anything else that I am doing wrong, I am a newbie in this area. THanks
First, instead of binding the view to a list of students, bind the model to your Class object that has a list of students in it. That way, when you submit (post), you are sending the whole Model object into the Controller.
Change your AddStudentsPost method to take in Class object and do your logic there.
Finally, change the name of the "Class" object to something else, such as, "Course". Class should be reserved for actual classes so not to cause confusion.
You aren't far off, so keep going

Localhost not found error appears when trying to go to a different page - ASP.NET CORE MVC

I am currently working on a basic To Do List on ASP.NET CORE. I have a button on top of the To-Do list to says "Add Task" upon clicking on the button you'll be re-directed to a Create Task Form. At the moment when click on the Add Task button to be re-directed to the form I am getting a localhost not found error. The URL is correct as it says http://localhost:51797/Todo/Create but my .cshtml page does not appear. I'm new to ASP.Net so apologies if the reason is obvious but I have gone through my code and I cant seem to find why this is happening.
[HttpPost]
[ActionName("Create")]
public ActionResult Create(int? id, string newText)
{
int i = id ?? 0;
TodoListItem toDo = _todoListService.GetList(i);
toDo.Text = newText; //Set new text
_todoListService.WriteToFile(toDo);
return RedirectToAction("Index");
}
}
This is my Create.cshtml page
#model TodoListItem
#{
ViewData["Title"] = "Create";
}
<h2>Add Task</h2>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Text" class="control-label"></label>
<input asp-for="Text" class="form-control" name="newText" />
<span asp-validation-for="Text" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
app.UseMvc(routes =>
routes.MapRoute(
name: "create",
template: "{controller=Todo}/{action=Create}");
});
You need an HTTPGET attribute for the GET action, which should return the create view with an empty model.
public IActionResult Create()
{
return View(new TodoListItem());
}
So when you click on Add Task, it will execute this action method and returns the create view.

I want to add products to my web page from database but in a custom div that I already have (ASP.NET)

I have this problem where I created a shopping site with ASP.NET, but I want to when a client adds a product I want that product to be in a special div that I created that contains the image and the description of the product and the price and when they click on it they go to a blank page that contains all the info of that product.
I don't know how to show information from the database in a div, I only show it in gridview that's all I know plus I want when they search a product the result will be shown in the same way.
*****UPDATE*****
//this is what i tried for now but it didnt work it
//This is my query
SELECT img, Détails FROM Produit WHERE (id_Prod = #id_Prod).
//And this is what im trying now
<asp:Repeater runat="server" ID="reptater">
<ItemTemplate<section<asp:HyperLinkID="HyperLink1"runat="server"NavigateUrl="~/Accueil.aspx"> <div class="gallery"><asp:Image ID="Image1" ImageUrl="<%#Eval("img") %>"runat="server"width="600"height="400"/> <div class="desc"><%#Eval("Détails") %></div> </div> </asp:HyperLink> </section></ItemTemplate></asp:Repeater>.
// c# :
reptater.DataSource = SqlDataSource1;
reptater.DataBind();
In your controller that you update to database, you will return a view with the model that contains a list of updated itens.
public ActionResult AssignTask()
{
var model = db.Employees.Select(x => new EmployeeViewModel
{
ID = x.id,
Name = x.Name
}).ToList();
return View(model);
}
Your new view.
#model List<EmployeeViewModel>
<h2>AssignTask</h2>
<div class="row">
<div class="form-group">
<div style="overflow-y:scroll; overflow-x:hidden; height:400px;">
#foreach (var item in Model)
{
<div class="col-lg-4 col-md-4">
<label>#item.Name</label>
<input type="checkbox" class="checkbox" name="SelectEmp" value="#item.ID" />
</div>
}
</div>
</div>
</div>

RedirectToAction after ajax form submit in Asp.net Core

I have a view named Index and a PartialView named '_Addbook' that shown as a bootstrap modal. In the partialView insert data into database using ajax form.
Index view :
<div class="panel panel-primary">
<div class="panel-body">
<div class="btn-group">
<a class="btn btn-primary marginbutoon" id="showBookgroup" data-toggle="modal" asp-action="AddBook"
data-target="#modal-book">
<i class="glyphicon glyphicon-plus"></i>
Add Book
</a>
</div>
</div>
Partialview :
#model WebApplication1.Models.Book
<form asp-controller="Home" asp-action="AddBook" id="myform"
data-ajax="true" data-ajax-method="POST"
data-ajax-mode="replace" data-ajax-update="#myform">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Add Book</h4>
</div>
<div class="modal-body form-horizontal">
<div class="row">
<div class="form-group">
<label asp-for="BookName" class="col-sm-3 control-label"></label>
<div class="col-lg-6">
<input asp-for="BookName" class="form-control" />
<span asp-validation-for="BookName" class="text-danger"></span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
Controller :
[HttpGet]
public IActionResult AddBook()
{
var book = new Book();
return PartialView("_AddBooks", book);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddBook(Book model)
{
if (ModelState.IsValid)
{
using (var db = _Context.GetRequiredService<ApplicationDbContext>())
{
db.bookgroups.Add(model);
db.SaveChanges();
}
return RedirectToAction("Index");
}
else
{
return PartialView("_Addbooks", model);
}
}
The data is stored correctly in the database and modal hide after submit but index view shows Mixed up.
How can i Redirect after ajax submit?
Your current form is setup to do ajax form post. So when the response is received from the server, it will replace the inner html of the form tag. So with your current code, it will basically makes a GET call to the Index action and the response of that will be loaded to the form tag.
If you want to do a redirect, but still want to have the model validation works, You may return a view result back, which has some javascript code which does the redirection.
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddBook(Book model)
{
if (ModelState.IsValid)
{
//Your code to store data
return PartialView("_AddedSuccessfully");
}
return PartialView("_AddBooks", model);
}
And in the _AddedSuccessfully.cshtml partial view will have only the below content, which is the javascript for redirect to /Home/Index
<script>
window.location.href = '#Url.Action("Index","Home")';
</script>
EDIT : As per the comment
how can i make it dynamically. because i have several partial view in
my project and i want pass ControllerName and ActionName as a
parameters to _AddedSuccessfully.cshtml?
You can pass it from your view to the action method and from there to the partial view
Just add a hidden input element to the Add form, just above your submit button and use Url.Action helper method to generate the url you want to redirect to, after saving successfully.
<input type="hidden" name="redirectUrl" value="#Url.Action("Index","Home")" />
<input type="submit" class="btn btn-primary" value="Submit"/>
Now, add a new parameter to your action method with the same name as the hidden input. Pass that string value as the model of the view when you call the PartialView method for _AddedSuccessfully view.
[HttpPost]
public IActionResult AddBook(Book model,string redirectUrl)
{
if (ModelState.IsValid)
{
// to do : Save
return PartialView("_AddedSuccessfully", redirectUrl);
}
return PartialView("_AddBook", model);
}
Now you need to udpate the partial view to be strongly typed to string and use the model of the view for redirect.
#model string
<script>
window.location.href = '#Model';
</script>
You can use FormHelper to create ajax forms, ajax redirects, showing notifications and to do many things on ASP.NET Core. Also, FormHelper helps you to transform server-side validations to client-side.
It's so easy to use. You just need to add asp-formhelper="true" to your form tag.
<form asp-formhelper="true" asp-controller="Home" asp-action="Save">
// <input...
// ...
</form>
You can check it's documentation on FormHelper GitHub Page. And you can download that package from Nuget.

MVC HttpPost receives a null parameter

The controller file in the application HomeController.cs, defines the two controls SetPowerOff and [HttppPost] SetPowerOff.
public ActionResult SetPowerOff(int ID, string deepness)
{
.............
if (Request.IsAjaxRequest())
{
var viewModel = new HomeSetPowerOffViewModel()
{
//List of devices
Devicelist = list,
age = 18
};
return PartialView("_SetPowerOff", viewModel);
}
else
{
return HttpNotFound();
}
}
[HttpPost]
public ActionResult SetPowerOff(HomeSetPowerOffViewModel homeSetPowerOffViewModel)
{
}
The Partial View returns the devices in a list.
#using (Html.BeginForm("SetPowerOff", "Home", FormMethod.Post, new { #class = "form-horizontal" }))
{
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">X</button>
<h3 id="myModalLabel">Devices information</h3>
</div>
<div class="modal-body ">
<div class="row-fluid">
<div class="span12">
<ul>
#foreach (var devices in Model.Devicelist)
{ <li>
#devices.Name;
</li>
}
</ul>
</div>
</div>
</div>
<div class="modal-footer">
#Html.ActionLink("Cancel", "Index", "Home", new { #class = "btn btn-danger" })
<button type="submit" class="btn btn-success">
Ok
</button>
</div>
}
After I press the Ok button on the Partial View it goes to the HttpPost request. Here the homeSetPowerOffViewModel received is null and the age is 0. I would very much like to know why is resetting them.
Thanks for your time!
you dont have any inputs in your form so there is nothing to submit
Your view<form>does not contain the form field like <input><select><textarea> for the age field.
So when you submit, it will be set to default integer value 0
Assuming age property of HomeSetPowerOffViewModel is a type of integer (int)
On post you receive hidden or any other input fields ( dropdowns, textbox and so on ). There is no such fields in your form. ( you are not filling the model in any way )
Althought, you can submit with ajax and you can send whatever you want to your controller

Categories

Resources