How to use Simple Ajax Beginform in Asp.net MVC 4? [closed] - ajax

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am new in Asp.net MVC and i researched about Ajax.BeginForm but when i apply codes it did not work. Can you share very simple example with Ajax.Beginform with View, Controller, Model?
Thanks.

Simple example: Form with textbox and Search button.
If you write "name" into the textbox and submit form, it will brings you patients with "name" in table.
View:
#using (Ajax.BeginForm("GetPatients", "Patient", new AjaxOptions {//GetPatients is name of method in PatientController
InsertionMode = InsertionMode.Replace, //target element(#patientList) will be replaced
UpdateTargetId = "patientList",
LoadingElementId = "loader" // div with .gif loader - that is shown when data are loading
}))
{
string patient_Name = "";
#Html.EditorFor(x=>patient_Name) //text box with name and id, that it will pass to controller
<input type="submit" value="Search" />
}
#* ... *#
<div id="loader" class=" aletr" style="display:none">
Loading...<img src="~/Images/ajax-loader.gif" />
</div>
#Html.Partial("_patientList") #* this is view with patient table. Same view you will return from controller *#
_patientList.cshtml:
#model IEnumerable<YourApp.Models.Patient>
<table id="patientList" >
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Number)
</th>
</tr>
#foreach (var patient in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => patient.Name)
</td>
<td>
#Html.DisplayFor(modelItem => patient.Number)
</td>
</tr>
}
</table>
Patient.cs
public class Patient
{
public string Name { get; set; }
public int Number{ get; set; }
}
PatientController.cs
public PartialViewResult GetPatients(string patient_Name="")
{
var patients = yourDBcontext.Patients.Where(x=>x.Name.Contains(patient_Name))
return PartialView("_patientList", patients);
}
And also as TSmith said in comments, don´t forget to install jQuery Unobtrusive Ajax library through NuGet.

All This Work :)
Model
public partial class ClientMessage
{
public int IdCon { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
Controller
public class TestAjaxBeginFormController : Controller{
projectNameEntities db = new projectNameEntities();
public ActionResult Index(){
return View();
}
[HttpPost]
public ActionResult GetClientMessages(ClientMessage Vm) {
var model = db.ClientMessages.Where(x => x.Name.Contains(Vm.Name));
return PartialView("_PartialView", model);
}
}
View index.cshtml
#model projectName.Models.ClientMessage
#{
Layout = null;
}
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script>
//\\\\\\\ JS retrun message SucccessPost or FailPost
function SuccessMessage() {
alert("Succcess Post");
}
function FailMessage() {
alert("Fail Post");
}
</script>
<h1>Page Index</h1>
#using (Ajax.BeginForm("GetClientMessages", "TestAjaxBeginForm", null , new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "SuccessMessage",
OnFailure = "FailMessage" ,
UpdateTargetId = "resultTarget"
}, new { id = "MyNewNameId" })) // set new Id name for Form
{
#Html.AntiForgeryToken()
#Html.EditorFor(x => x.Name)
<input type="submit" value="Search" />
}
<div id="resultTarget"> </div>
View _PartialView.cshtml
#model IEnumerable<projectName.Models.ClientMessage >
<table>
#foreach (var item in Model) {
<tr>
<td>#Html.DisplayFor(modelItem => item.IdCon)</td>
<td>#Html.DisplayFor(modelItem => item.Name)</td>
<td>#Html.DisplayFor(modelItem => item.Email)</td>
</tr>
}
</table>

Besides the previous post instructions, I had to install the package Microsoft.jQuery.Unobtrusive.Ajax and add to the view the following line
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

Related

ASP.NET Core 6 MVC : HTML table to view model collection

Starting up with ASP.NET Core 6 MVC and in my case I have one view which lists few properties of one object and then some other for their children in a editable table (user can edit the values)
View model has the properties and an IEnumerable of the children:
public class MyObjectViewModel
{
public String Id { get; set; }
public String Descr { get; set; }
public IEnumerable<ChildrenObject> Children { get; set; }
public MyObjectViewModel()
{
Children = Enumerable.Empty<ChildrenObject>();
}
public class ChildrenObject
{
public String? Id { get; set; }
public String? Name { get; set; }
}
}
All under the same form:
#using (Html.BeginForm("Save", "Controller", FormMethod.Post))
{
<input type="submit" value="SAVE"/>
<br />
#Html.LabelFor(model => model.Id)
#Html.TextBoxFor(model => model.Id, new { #readonly = "readonly" })
<br />
#Html.LabelFor(model => model.Descr)
#Html.EditorFor(model => model.Descr)
<br />
<table>
<tbody>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
#foreach (var child in Model.Children)
{
<tr>
<td>#child.Id</td>
<td><input class="ef-select" type="text" value="#child.Name"></td>
</tr>
}
</tbody>
</table>
}
So when the button is pressed the data is dumped back to the model to perform the SAVE action in the controller.
All ok for the simple fields (I can get the data in the controller as the view model), but not sure how to accomplish it with the table / children property...
Any simple way without needing to use JS to serialise or pick up the data from the table?
Thanks
If you want to pass id and name of ChildrenObject in table,you can try to add hidden inputs for the Id,and set name attribute for name inputs:
#{var count = 0; }
#foreach (var child in Model.Children)
{
<tr>
<td>
#child.Id
<input value="#child.Id" name="Children[#count].Id" />
</td>
<td><input class="ef-select" type="text" value="#child.Name" name="Children[#count].Name"></td>
</tr>
count++;
}

MVC4 How to get the data in partial view when parent view click submit

MVC4 How to get the data in partial view when parent view click submit
I create a edit page for user update the data, the parent view show some of book details and partial view is a loop show the status of each book. Also, the parent view have a submit button for update both of partial view and parent view, but when I click the submit only parent view data can update and partial view still not update. The code below:
Model:
public class LibraryInventory
{
public decimal LibraryID { get; set; }
public string Title { get; set; }
public List<LibraryItem> Entities { get; set; }
}
public class LibraryItem
{ public decimal StatusID { get; set; }
public string Location { get; set; }
public decimal BorrowedBy { get; set; }
}
Controller :
public ActionResult EditRecord(string ID)
{
DataTable dt = (DataTable)Session["EditGridData"];
LibraryInventory record = new LibraryInventory(dt.Rows[0]);
dt = LibraryEditBLL.GetEditItems(ID);
if (results.ToList().Count > 0)
{
record.Entities = LibraryItem.ConvertToLibraryEntity(dt).ToList();
}
return View(record);
}
[HttpPost]
public ActionResult EditRecord(string FormButton, LibraryInventory model)
{
switch (FormButton)
{
case "Submit":
if (ModelState.IsValid)
{
LibraryEditBLL.UpdateInventoryLibrary(model);
}
return View("EditRecord",record);
default:
return RedirectToAction("Edit"); //other page not need check
}
View :
#model XXX.Models.LibraryModels.LibraryInventory
#using (Html.BeginForm("EditRecord", "Library", FormMethod.Post, new { enctype = "multipart/form-data" })){
#Html.HiddenFor(m =>m.LibraryID)
<table>
<tr>
<td>#Html.TextBoxFor(m => m.Title)</td>
#for (var i = 0; i < #Model.Entities.Count; i++)
{
#Html.Partial("EditItem", #Model.Entities[i])
}
</tr>
</table>
}
#model XXX.Models.LibraryModels.LibraryItem
<tr>
<td> #Html.DropDownListFor(m => m.StatusID) </td>
<td> #Html.DropDownListFor(m => m.Location)</td>
<td> #Html.DropDownListFor(m => m.BorrowedBy) </td>
</tr>
Try this code for your view. And no need of partialview for this simple scenario.
#model XXX.Models.LibraryModels.LibraryInventory
#using (Html.BeginForm("EditRecord", "Library", FormMethod.Post, new { enctype = "multipart/form-data" })){
#Html.HiddenFor(m =>m.LibraryID)
<table>
<tr>
<td>#Html.TextBoxFor(m => m.Title)</td>
</tr>
#for (var i = 0; i < Model.Entities.Count; i++)
{
<tr>
<td> #Html.DropDownListFor(m => Model.Entities[i].StatusID) </td>
<td> #Html.DropDownListFor(m => Model.Entities[i].Location)</td>
<td> #Html.DropDownListFor(m => Model.Entities[i].BorrowedBy) </td>
</tr>
}
</table>
}

post a form using ajax inside a partial view which loaded on another view

I'm trying to manage the keywords for each page. i have this class
public class Keyword
{
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Display(Name = "آدرس")]
public string Address { get; set; }
[Display(Name = "کلمات کلیدی")]
public string KeyWords { get; set; }
[Display(Name = "شرح صفحه")]
public string Description { get; set; }
}
and this is my controller
[Authorize(Roles = "admins")]
public ActionResult Create(string Address="")
{
Keyword keyword = db.Keywords.Where(k => k.Address == Address).FirstOrDefault();
if (null == keyword)
{
keyword = new Keyword() { Address = Address };
}
return PartialView(keyword);
}
[HttpPost]
[Authorize(Roles = "admins")]
public ActionResult Create(Keyword keyword)
{
keyword.Address = Request.UrlReferrer.PathAndQuery;
if (db.Keywords.Count(k => k.Address == keyword.Address) > 0)
{
var model = db.Keywords.Where(k => k.Address == keyword.Address).FirstOrDefault();
model.Description = keyword.Description;
model.KeyWords = keyword.KeyWords;
if (ModelState.IsValid)
{
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
//return Redirect(Request.UrlReferrer.AbsoluteUri);
}
}
else if (ModelState.IsValid)
{
db.Keywords.Add(keyword);
db.SaveChanges();
//return Redirect(Request.UrlReferrer.AbsoluteUri);
}
return PartialView(keyword);
}
and this the partial view
#model Stockala.Models.Keyword
#using (Ajax.BeginForm("Create", "Keyword", new AjaxOptions() { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "keywords-div" }))
{
#Html.ValidationSummary(true)
#Html.AntiForgeryToken()
<fieldset>
<legend>کلمات کلیدی</legend>
<table class="fields">
<tr>
<td class="label">
#Html.LabelFor(model => model.KeyWords) :
</td>
<td class="editor-field">
#Html.TextBoxFor(model => model.KeyWords, new { style = "width:600px;" })
#Html.ValidationMessageFor(model => model.KeyWords)
</td>
</tr>
<tr>
<td class="label">
#Html.LabelFor(model => model.Description) :
</td>
<td class="editor-field">
#Html.TextAreaFor(model => model.Description, new { style = "width:600px;" })
#Html.ValidationMessageFor(model => model.Description)
</td>
</tr>
<tr>
<td colspan="2">
<p>
<input id="keysubmit" type="submit" value="تایید" class="button"/>
</p>
</td>
</tr>
</table>
</fieldset>
}
and this is how i rendered the partial view inside my _layout.chtml
<div id="main">
#RenderBody()
#if (User.IsInRole("admins"))
{
<div id="keywords-div">
#Html.Action("Create", "Keyword", new { Address = Request.Url.PathAndQuery })
</div>
}
</div>
but here is a the problem. when i submit the form, it goes to the Keyword controller and the browser shows only the partial view, but i want to just submit the form and stay in the current page.
This way worked for me. Adapted to your situation:
#model Stockala.Models.Keyword
#using (Ajax.BeginForm("Create", "Keyword", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "keywords-div" }))
{
<div id="keywords-div">
//Rest of the form body
</div>
}
remove the '()' from your "new AjaxOptions ()"

How to pass a list of objects instead of one object to a POST action method

I have the following GET and POST action methods:-
public ActionResult Create(int visitid)
{
VisitLabResult vlr = new VisitLabResult();
vlr.DateTaken = DateTime.Now;
ViewBag.LabTestID = new SelectList(repository.FindAllLabTest(), "LabTestID", "Description");
return View();
}
//
// POST: /VisitLabResult/Create
[HttpPost]
public ActionResult Create(VisitLabResult visitlabresult, int visitid)
{
try
{
if (ModelState.IsValid)
{
visitlabresult.VisitID = visitid;
repository.AddVisitLabResult(visitlabresult);
repository.Save();
return RedirectToAction("Edit", "Visit", new { id = visitid });
}
}
catch (DbUpdateException) {
ModelState.AddModelError(string.Empty, "The Same test Type might have been already created,, go back to the Visit page to see the avilalbe Lab Tests");
}
ViewBag.LabTestID = new SelectList(repository.FindAllLabTest(), "LabTestID", "Description", visitlabresult.LabTestID);
return View(visitlabresult);
}
Currently the view display the associated fields to create only one object,, but how i can define list of objects instead of one object to be able to quickly add for example 10 objects at the same “Create” request.
My Create view look like:-
#model Medical.Models.VisitLabResult
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#section scripts{
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>VisitLabResult</legend>
<div class="editor-label">
#Html.LabelFor(model => model.LabTestID, "LabTest")
</div>
<div class="editor-field">
#Html.DropDownList("LabTestID", String.Empty)
Your viewModel
public class LabResult
{
public int ResultId { get; set; }
public string Name { get; set; }
//rest of the properties
}
Your controller
public class LabController : Controller
{
//
// GET: /Lab/ns
public ActionResult Index()
{
var lst = new List<LabResult>();
lst.Add(new LabResult() { Name = "Pravin", ResultId = 1 });
lst.Add(new LabResult() { Name = "Pradeep", ResultId = 2 });
return View(lst);
}
[HttpPost]
public ActionResult EditAll(ICollection<LabResult> results)
{
//savr results here
return RedirectToAction("Index");
}
}
Your view
#model IList<MvcApplication2.Models.LabResult>
#using (Html.BeginForm("EditAll", "Lab", FormMethod.Post))
{
<table>
<tr>
<th>
ResultId
</th>
<th>
Name
</th>
</tr>
#for (int item = 0; item < Model.Count(); item++)
{
<tr>
<td>
#Html.TextBoxFor(modelItem => Model[item].ResultId)
</td>
<td>
#Html.TextBoxFor(modelItem => Model[item].Name)
</td>
</tr>
}
</table>
<input type="submit" value="Edit All" />
}
Your view will be rendered as follows, this array based naming convention makes it possible for Defaultbinder to convert it into ICollection as a first parameter of action EditAll
<tr>
<td>
<input name="[0].ResultId" type="text" value="1" />
</td>
<td>
<input name="[0].Name" type="text" value="Pravin" />
</td>
</tr>
<tr>
<td>
<input name="[1].ResultId" type="text" value="2" />
</td>
<td>
<input name="[1].Name" type="text" value="Pradeep" />
</td>
</tr>
If I understand your question correctly,
you want to change your view to be a list of your model object #model List, then using a loop or however you wish to do it, create however many editors you need to for each object
then in your controller your receiving parameter of create will be a list of your model instead too.

Partial postback of page with dropdownlist using AJAX on MVC3 page EF4

I have a dropdownlist which lists Country names
When user select any country from dropdown list.Based on the country selection, I need data(AgencyName, AgencyAddr,Pincode) to be loaded from database and fill the TextBoxs on the right side.The selected country in the dropdown should remain selected.
on selection change of dropdownlist ,I do not want the entire page to postback .Please help me
Here is my EF4 - ModelClasses
public class Country
{
public int CountryID { get; set; }
public string CountryName { get; set; }
}
public class AgencyInfo
{
public int CountryID { get; set; }
public string AgencyName { get; set; }
public string AgencyAddr { get; set; }
public int Pincode { get; set; }
}
Here is my MVC4 razor page Index.cshtml
#using (Ajax.BeginForm(
"Index",
"Home",
new AjaxOptions { UpdateTargetId = "result" }
))
{
#Html.DropDownList("SelectedCountryId", Model.CountryList, "(Select one event)")
}
<div id=’result’>
<fieldset>
<legend>Country Details: </legend>
<div>
<table>
<tr>
<td>
<span>Country Name </span>
<br />
#Html.EditorFor(model => model.Countries.Name)
#Html.ValidationMessageFor(model => model. Countries.Name)
</td>
<td>
<span>Agency Name </span>
<br />
#Html.EditorFor(model => model.AgencyInfo.AgencyName)
#Html.ValidationMessageFor(model => model.AgencyInfo.AgencyName)
</td>
</tr>
<tr>
<td>
<span>Address Info </span>
<br />
#Html.EditorFor(model => model. AgencyInfo.Address)
#Html.ValidationMessageFor(model => model. AgencyInfo.Address)
</td>
<td>
<span>Pin Code </span>
<br />
#Html.EditorFor(model => model. AgencyInfo.PinCode)
#Html.ValidationMessageFor(model => model. AgencyInfo.PinCode)
</td>
</tr>
<tr>
<td>
<input type="submit" value="Modify" /><input type="submit" value="Delete" />
</td>
<td>
<input type="submit" value="Save" /><input type="submit" value="View Resources" />
</td>
</tr>
</table>
</div>
</fieldset>
</div > #end of result div#
Any suggestions ? Thank you
You want to use ajax.
Add an event handler to monitor the selection change. When the drop down changes, get the current country and send the ajax request. When the ajax request returns update the DOM with jQuery.
Example view:
<p id="output"></p>
<select id="dropDown"><option>Option 1</option>
<option>Option 2</option></select>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$("#dropDown").change(function () {
var selection = $("#dropDown").val();
var dataToSend = {
country: selection
};
$.ajax({
url: "home/getInfo",
data: dataToSend,
success: function (data) {
$("#output").text("server returned:" + data.agent);
}
});
});
});
</script>
Example controller method:
public class HomeController : Controller
{
[HttpGet]
public JsonResult GetInfo(string country)
{
return Json(new { agent = country, other = "Blech" }, JsonRequestBehavior.AllowGet);
}
}
Some other examples:
adding a controller method to handle ajax request:
http://www.cleancode.co.nz/blog/739/ajax-aspnet-mvc-3
calling ajax and updating DOM:
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax2

Resources