Working on view with two forms on one controller in mvc 5 - asp.net-mvc

I have one drop down box. Based on the selected item of dropdownbox i want to generate form below on same view, Please find the code below.
[HttpGet]
public ActionResult BindDropDown()
{
ViewBag.doctype = new SelectList(db.DocTypeMasters, "Id", "DocTypeName");
return View();
}
[HttpPost]
public ActionResult BindDropDown(string DocType)
{
String Doc = DocType.Trim();
return View();
}
this is my view code
#model C3CardKYC.Models.DocTypeMaster
#{
ViewBag.Title = "BindDropDown";
}
<h2>BindDropDown</h2>
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#MyIdAndName').change(function () {
var DocType = $("#MyIdAndName option:selected").text();
alert(DocType);
$.ajax({
url: '#Url.Action("BindDropDown", "Document")',
type: 'POST',
data: { DocType: DocType },
success: function (result) {
alert('success')
}
})
});
});
</script>
<fieldset>
<legend>DocTypeMaster</legend>
#*Select Document Type: #Html.DropDownList("doctype", "Select");*#
#Html.DropDownList("MyIdAndName", ViewBag.doctype as SelectList, " -- Select Document Type -- ")
</fieldset>
<p id="hi">
#Html.ActionLink("Back to List", "Index")
</p>
<div id="hi">
#using (Html.BeginForm("BindDropDown", "Document", FormMethod.Post, new { id = "submitForm" }))
{
<fieldset>
<ol>
<li>
#Html.LabelFor(Model => Model.DocTypeName)
#Html.TextBoxFor(Model => Model.DocTypeName, new { maxlength = 50 })
#Html.ValidationMessageFor(Model => Model.DocTypeName)
</li>
</ol> <button type="submit" id="btnSave" name="Command" value="Save">Save</button>
<button type="submit" id="btnSubmit" name="Command" value="Submit">Submit</button>
<button type="submit" id="btnCancel" name="Command" value="Cancel" onclick="$('#submitForm').submit()">Cancel (Server Side)</button>
</fieldset>
}
</div>
When i run this below error is coming.
There is no ViewData item of type 'IEnumerable' that has the key 'MyIdAndName'.
and if i select the item frm dropdown then only below form should appear. Please suggest

Related

Loading partialView through ajax not working

i am trying to show order Summary through partial View and ajax.Request is going to server but my action method of Showsummary never hits. i want to summary of order through partial view.
[HttpPost]
public PartialViewResult Showsummary(OrderViewModel model)
{
try
{
var p = model.Packages.SelectMany(x => x.Packages).Select(y => new OrderPackagesViewModel()
{
PkgName = y.PkgName,
pkg_Id = y.id,
Ser_Id = y.Ser_Id,
Quantity = y.Quantity,
price = (y.TotalPrice - (y.DiscountPercent / 100 * y.TotalPrice)) * y.Quantity
}).ToList();
model.OrderPackages = p;
return PartialView("OrderSummary", model);
}
catch
{
return PartialView("OrderSummary", model);
}
}
My Ajax
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
$.ajax({
type: "POST",
url: "/Order/Showsummary",
data: $("form.signup-form").serialize(),
success: function (data) {
console.log(data)
$('#page_2').hide();
$('#page_3').show();
$('#page_3').html(data);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
})
//Html Code
<div id="page_1">
<input asp-for="cus_name" placeholder="First Name" >
<input asp-for="Email" placeholder="Email" >
<select asp-for="Country" class="ui search dropdown">
<option value="">Select Country</option>
<option value="AF">Afghanistan</option>
<option value="AX">Ă…land Islands</option>
</select>
<input asp-for="cus_phone" placeholder="Phone Number"/>
<select asp-for="FirstPreferences" class="custom-select mr-sm-2"
asp-items="#(newSelectList(Preferences))">
<option value="">Select</option>
</select>
<select asp-for="FirstPreferedTimeStart" class="menu">
<option value="">HH:MM</option>
<option value="00:00:00">00:00</option>
<option value="01:00:00">01:00</option>
</select>
<textarea asp-for="Message" class="form-control"> </textarea>
</div>
//Page2 details of packages available. It is list of GroupByServices which contain fields ser_id Ser_Name and List of ServicePackages.
<div id="page_2" style="display:none">
<div>
<h1 id="heading">Choose a Package!</h1>
</div>
<div class="buttons">
#foreach (var services in Model.Packages)
{
<a href="#service_#services.Ser_Id"><div class="logo-p">
<h2>#services.Ser_Name</h2></div></a>
}
</div>
<!-- packages -->
#for (int i = 0; i < Model.Packages.Count; i++)
{
<div class="packages" id="service_#Model.Packages[i].Ser_Id">
<h1 id="custom-website-design">
#Model.Packages[i].Ser_Name
</h1>
<div class="packs-content">
#for (int j = 0; j < Model.Packages[i].Packages.Count(); j++)
{
<div class="pack1">
<div class="pack-price">
<div>
<input asp-for="#Model.Packages[i].Packages[j].id" hidden />
<input asp-for="#Model.Packages[i].Packages[j].PkgName" hidden />
<input asp-for="#Model.Packages[i].Packages[j].Ser_Id" hidden />
<input asp-for="#Model.Packages[i].Packages[j].Ser_Name" hidden />
<h1>#Model.Packages[i].Packages[j].PkgName</h1>
<p>#Model.Packages[i].Packages[j].Ser_Name PACKAGE</p>
</div>
<p>$#Model.Packages[i].Packages[j].TotalPrice</p>
<input asp-for="#Model.Packages[i].Packages[j].TotalPrice" hidden />
</div>
<div class="pack-features">
<div class=""></div>
#foreach (var features in Model.Packages[i].Packages[j].Description)
{
<h2>#features</h2>
}
</div>
<div class="pack-order">
<div class="row-1">
#{
double discount = (Model.Packages[i].Packages[j].DiscountPercent / 100 * Model.Packages[i].Packages[j].TotalPrice);
double PriceAfterDiscount = Model.Packages[i].Packages[j].TotalPrice - discount;
}
<p>SPECIAL DISCOUNT</p>
<P>-$#discount</P>
</div>
<div class="row-2">
<p>FINAL PRICE FOR LIMITED TIME</p>
</div>
<div class="row-3">
<a asp-controller="Packages" asp-action="Detail" asp-route-id="#Model.Packages[i].Packages[j].id" target="_blank">view details</a>
<h1>$#PriceAfterDiscount</h1>
<input asp-for="#Model.Packages[i].Packages[j].DiscountPercent" hidden />
</div>
<div class="row-4">
<h4>Add To Buying List</h4>
<div class="input-group mb-3 order-btn-pack">
<div class="input-group-prepend">
<div class="input-group-text">
<input asp-for="#Model.Packages[i].Packages[j].is_selected" aria-label="Checkbox for following text input">
</div>
</div>
<input asp-for="#Model.Packages[i].Packages[j].Quantity" value="1" min="1" required placeholder="Quantity" class="form-control" aria-label="Text input with checkbox">
</div>
</div>
<div class="row-5">
<p>Discuss this offer with expert</p>
<div class="discuss">
<p>12345467889</p>
<p id="chat-btn_10">Live Chat</p>
</div>
</div>
</div>
</div>
}
<input asp-for="HoldPackage" hidden/>
</div>
</div>
}
<div>
<button type="button" class="btn btn-danger px-2 btn-lg" onclick="PageBack(this.parentElement.parentElement)">Back</button>
<button type="button" class="btn btn-danger px-2 btn-lg" id="summary">Summary!</button>
</div>
</div>
Edit!!!!
i have changed this line in ajax now it start hitting my controller action but still all form values are empty seems model binding is unable to recognize my fields
**const model= $("form").serialize()**
console.log(model); //data is there thats fine
and in ajax
data: { model },
my model have field called packages which is list of some fields and inside it there is one another list.
One thing is clear. $("form").serialize() is not working in my case its giving me 415 Unsupported Media Type client error response. I think problem is due to nested List
I have checked your code on my side with a simple OrderViewModel object, it works well. I suggest you could try to add '[FromBody]' in the action method, Like this:
....
Edit
According your description, it seems that you are using the Nested List and meet 415 error when using the [FromBody]. I have modified the sample code, in the action method, it's not using the [FromBody] attribute and in the JQuery Ajax method, there is no need to use the JSON.stringify method to change the JavaScript object. More detail information, please check the following code:
Model Class (Suppose the OrderViewModel contain a List):
public class OrderViewModel
{
public int OrderId { get; set; }
public string OrderName { get; set; }
public List<Package> Packages { get; set; }
}
public class Package
{
public int Pid { get; set; }
public string PackageTitle { get; set; }
}
Code in the Controller:
/// <summary>
/// //display the order
/// </summary>
/// <returns></returns>
public IActionResult ShowOrder()
{
OrderViewModel ovm = new OrderViewModel()
{
OrderId = 1001,
OrderName = "order 1",
Packages = new List<Package>()
{
new Package(){ Pid=101, PackageTitle="first Package"},
new Package(){ Pid=102, PackageTitle="second package"}
}
};
return View(ovm);
}
/// <summary>
/// JQuery ajax post method
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
[HttpPost]
public PartialViewResult Showsummary(OrderViewModel model)
{
try
{
//...
return PartialView("OrderSummary", model);
}
catch
{
return PartialView("OrderSummary", model);
}
}
ShowOrder.cshtml:
#model MVCSample.Models.OrderViewModel
#{
ViewData["Title"] = "ShowOrder";
}
<div class="row">
<div class="col-md-4">
<form asp-action="Showsummary" asp-controller="Home" method="post" class="signup-form">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="OrderId" class="control-label"></label>
<input asp-for="OrderId" class="form-control" />
<span asp-validation-for="OrderId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="OrderName" class="control-label"></label>
<input asp-for="OrderName" class="form-control" />
<span asp-validation-for="OrderName" class="text-danger"></span>
</div>
<div id="packages">
#for (int i = 0; i < Model.Packages.Count; i++)
{
<div class="form-group">
<label asp-for="#Model.Packages[i].Pid" class="control-label"></label>
<input asp-for="#Model.Packages[i].Pid" class="form-control" />
<span asp-validation-for="#Model.Packages[i].Pid" class="text-danger"></span>
<br />
<label asp-for="#Model.Packages[i].PackageTitle" class="control-label"></label>
<input asp-for="#Model.Packages[i].PackageTitle" class="form-control" />
<span asp-validation-for="#Model.Packages[i].PackageTitle" class="text-danger"></span>
</div>
}
</div>
#*<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>*#
</form>
</div>
</div>
<div>
<input type="button" id="summary" value="Summary" />
<div id="page_3">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
//create a object to store the entered value.
var OrderViewModel = {};
//using jquery to get the entered value.
OrderViewModel.OrderId = $("input[name='OrderId']").val();
OrderViewModel.OrderName = $("input[name='OrderName']").val();
var packages = [];
//var count = $("#packages>.form-group").length; //you could use it to check the package count
$("#packages>.form-group").each(function (index, item) {
var package = {}
package.Pid = $(item).find("input[name='Packages[" + index + "].Pid']").val();
package.PackageTitle = $(item).find("input[name='Packages[" + index + "].PackageTitle']").val();
packages.push(package);
});
OrderViewModel.Packages = packages;
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: OrderViewModel,
success: function (data) {
console.log(data)
$('#page_3').html(data);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
</script>
Then the output as below:
Edit:
Besides, I also found that by using the above sample, if I just change the data: OrderViewModel to data: $("form.signup-form").serialize() (in the Ajax method), I could also get the OrderViewModel and the Packages in the action method.

Asp.net Core 2 and Knockout.js

Good morning I'm trying to add Anti Forgery Token to my application made using Knockout.js
This is my Model:
public partial class Course
{
[Key]
public int CourseID { get; set; }
public string CourseName { get; set; }
public string CourseDescription { get; set; }
}
This is my controller:
// POST: Home/Create
[HttpPost]
public string Create(Course course)
{
if (!ModelState.IsValid) return "Model is invalid";
_db.Courses.Add(course);
_db.SaveChanges();
return "Cource is created";
}
This is my View:
#model MVCCRUDKnockout.Models.Course
#{
ViewBag.Title = "Create";
}
<div class="form-horizontal">
<h4>Course</h4>
<hr>
<div class="form-group">
<label class="control-label col-md-2" for="CourseName">CourseName</label>
<div class="col-md-10">
<input class="form-control text-box single-line" id="CourseName" name="CourseName" type="text" value="" data-bind="value: CourseName">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="CourseDescription">CourseDescription</label>
<div class="col-md-10">
<input class="form-control text-box single-line" id="CourseDescription" name="CourseDescription" type="text" value="" data-bind="value: CourseDescription">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" data-bind="click: createCourse" value="Create" class="btn btn-default">
</div>
</div>
</div>
<div>
#Html.ActionLink("Back to List", "Read")
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/knockout-3.4.0.js"></script>
<script src="~/Scripts/KOScripts/KOCreate.js"></script>
This is my Script:
$(function () {
ko.applyBindings(modelCreate);
});
var modelCreate = {
CourseName: ko.observable(),
CourseDescription: ko.observable(),
createCourse: function () {
try {
$.ajax({
url: '/Home/Create',
type: 'post',
dataType: 'json',
data: ko.toJSON(this), //Here the data wil be converted to JSON
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
};
function successCallback(data) {
window.location.href = '/Home/Read/';
}
function errorCallback(err) {
window.location.href = '/Home/Read/';
}
Now I try to change the code:
1) adding [ValidateAntiForgeryToken] to the controller;
2) adding #Html.AntiForgeryToken() to the View.
My problem is that I cannot edit the Script to make it work properly.
How can I do this?

Replacing parent view with partial view from another partial view

This My Parent View In this i am calling partialview(_CityList.cshtml).
#model MedicalOrbit.City
#{
ViewBag.Title = "CreateCity";
}
<h2>Add City</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div id="Maindiv" class="col-lg-7">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>City Details</h5>
<div class="ibox-tools">
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
</div>
</div>
<div class="ibox-content">
<div class="row">
<div class="col-sm-6 b-r">
#*<hr />*#
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label>City Name:</label>
#*#Html.LabelFor(model => model.CityName, htmlAttributes: new { #class = "control-label col-md-2" })*#
<br>
<div >
#Html.EditorFor(model => model.CityName, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter City" } })
#Html.ValidationMessageFor(model => model.CityName, "", new { #class = "text-danger" })
</div>
</div>
<br>
<div>
<input type="submit" value="Create" class="btn btn-w-m btn-primary" />
<input type="submit" value="Cancel" class="btn btn-w-m btn-success" />
</div>
</div>
<div>
<div id="CityList" class="col-sm-6">
#*#Html.Partial("_CityList");*#
#Html.Action("CityList", "City")
</div>
</div>
</div>
</div>
</div>
</div>
}
<div id="Editdiv">
#Html.Action("EditCity", "City")
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Partial View(_CityList.cshtml)
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CityName)
</th>
<th>Action</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CityName)
</td>
<td>
#*#Html.ActionLink("Edit", "Edit", new { id = item.CityID })*#
#Ajax.ActionLink("Edit City", "EditCity", "City", new AjaxOptions()
{
UpdateTargetId = "Maindiv",
InsertionMode = InsertionMode.ReplaceWith
})|
#Html.ActionLink("Details", "Details", new { id = item.CityID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.CityID }) |
#Html.ActionLink("Area", "Area", new { #class = "btn btn-warning btn-circle btn-lg fa fa-times", id = item.CityID })
</td>
</tr>
}
</table>
following is my Controller Code
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MedicalOrbit.Controllers
{
public class CityController : Controller
{
MediOrbitDatabaseEntities db = new MediOrbitDatabaseEntities();
// GET: City
public ActionResult Index()
{
return View();
}
public ActionResult CityList()
{
return PartialView("_CityList", db.Cities.Where(x => x.status == false).ToList());
}
public ActionResult CreateCity()
{
return View();
}
// POST: City/CreateCity
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateCity(City city)
{
// TODO: Add insert logic here
if (ModelState.IsValid)
{
city.Users = "ashwini";
city.DateTime = DateTime.UtcNow;
city.status = false;
db.Cities.Add(city);
db.SaveChanges();
return RedirectToAction("CreateCity");
}
return View(city);
}
public ActionResult EditCity(int? id)
{
City city = db.Cities.Where(x => x.CityID == id).FirstOrDefault();
if (city == null)
{
return HttpNotFound();
}
return View(city);
}
// POST: /Admin/City/Edit
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditCity(City city)
{
if (ModelState.IsValid)
{
city.Users = "Ashwini";
city.DateTime = DateTime.UtcNow;
city.status = false;
db.Entry(city).State = EntityState.Modified;
db.SaveChanges();
RedirectToAction("CreateCity");
}
return PartialView("_EditCity",city);
}
}
}
Now what i want is in _CityList.cshtml partial view when user clicks the edit actionlink then main parent view should be replace with another partial view(_EditCity.cshmtl).how i can achieve this.i m not experience in mvc so plz help me.
I am showing you how to do partial views. Hopefully, you will have enough take away to utilize partial views within partial views, if you want.
There might be extra code to help you.
View:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexValid4</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function () {
$('#LOCATION_NUMBER').click(function () {
var store = $('#storeNbr').val();
this.href = this.href.split("?")[0];
this.href = this.href + '?LOCATION_NUMBER=' + encodeURIComponent(store);
});
})
</script>
</head>
<body>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">My Modal</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<label class="btnIEFix">You can also, Click in Grey Area Outside Modal To Close</label>
<button title="You can also, Click in Grey Area Outside Modal To Close" type="button" class="btn btn-secondary bootBtnMargin" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#Html.HiddenFor(r => r.storeNbr, new { id = "storeNbr" })
#*https://stackoverflow.com/questions/5838273/actionlink-routevalue-from-a-textbox*#
#Ajax.ActionLink(
"Trigger Ajax",
"ReleaseVersion",
null,
new AjaxOptions
{
UpdateTargetId = "result",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
},
new
{
id = "LOCATION_NUMBER"})
<div id="result"></div>
</body>
</html>
Controller:
public class HomeController : Controller
{
public PartialViewResult ReleaseVersion(string LOCATION_NUMBER = "")
{
return PartialView("_ReleaseVersion"); //, model
}
public ActionResult IndexValid4()
{
var storeViewModel = new StoreViewModel { storeNbr = 5 };
return View(storeViewModel);
}
_ReleaseVersion partial view in shared folder:
release version partial view

Partial view doesn't load inside current view

So I have this partial view:
#model QueryQuestionManager.Models.Domain.Answer
<script src="~/Scripts/DynamicList.js"></script>
<div class="editorRow">
#using (Html.BeginCollectionItem("Answers"))
{
<div>
#Html.LabelFor(x => x.AnswerText)
#Html.EditorFor(x => x.AnswerText)
</div>
delete
}
</div>
I want to load this partial view in my main view when someone clicks the link:
#model QueryQuestionManager.Models.Domain.Question
#{
ViewBag.Title = "Create";
}
<script src="~/Scripts/DynamicList.js"></script>
<br />
#using (Html.BeginForm(new { #class = "form", role = "form" }))
{
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(m => m.QuestionText)
</div>
<div class="form-control">
#Html.TextBoxFor(m => m.QuestionText)
#Html.ValidationMessageFor(m => m.QuestionText)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Category)
</div>
<div class="form-control">
#Html.TextBoxFor(m => m.Category)
#Html.ValidationMessageFor(m => m.Category)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Answers)
</div>
<br />
<div id="editorRows">
#foreach (var item in Model.Answers)
{
#Html.Partial("EditorRow", item);
}
</div>
#Html.ActionLink("Add another...", "BlankEditorRow", "Question", new { id = "addItem" })
<br />
<input type="submit" value="Save" class="btn btn-success" />
</div>
}
<br />
<div>
#Html.ActionLink("Back to List", "Index", "Home")
</div>
This is the action result from the controller
public ActionResult BlankEditorRow()
{
return PartialView("EditorRow", new Answer());
}
And then I have a javascript file for the dynamic adding and deleting partial views.
$('#addItem').click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) {
$('#editorRows').append(html);
}
});
return false;
});
$('a.deleteRow').live('click', function () {
$(this).parents('div.editorRow:first').remove();
return false;
});
But for some reason my partial view doesn't load inside my current view and it opens only the partial view.
Am I forgetting something?
I'm thinking you don't want that action link. I believe your jQuery click handler has the correct approach, but your action link is linking to your new URL (Question/BlankEditorRow) and you don't want that. Rather you just need to fetch this html, and insert it as you do, but WITHOUT navigating the main page to that URL.
Instead of the ActionLink, use an anchor tag and a hidden field.
<a id="addItem" href="#" />
<input type="hidden" id="partialViewAction" value="#Url.Action("BlankEditorRow","ControllerName")"
Now in your ajax call, instead of using the href property of the anchor, use the value of the hidden field.
url: $('#partialViewAction').val()

Facing issue while submitting Partial View using JQuery post

I have an Area like below.
Controller Class
public class AdminController : Controller
{
//
// GET: /Admin/Admin/
[HttpPost]
public ActionResult Index_partialPost(AdminModule model)
{
return PartialView("_PartialPage1", model);
}
[HttpGet]
public ActionResult Index_partial()
{
return PartialView("_PartialPage1");
}
[HttpGet]
public ActionResult Index()
{
AdminModule model = new AdminModule();
model.MyName = "My Name";
return View("Index", model);
}
}
View
#model _1.Areas.Admin.Models.AdminModule
#{
ViewBag.Title = "Index";
Layout = "~/Areas/Admin/Views/Shared/_LayoutPage1.cshtml";
}
<h2>
Index</h2>
<div id="myForm">
<p id="pid">
</p>
</div>
<input id="BTN" type="submit" value="Button" />
<script language="javascript" type="text/javascript">
$('#BTN').click(function(){
$('#pid').load("#Url.Action("Index_partial", "Admin")");
});
</script>
View
#model _1.Areas.Admin.Models.AdminModule
#{
ViewBag.Title = "Index";
Layout = "~/Areas/Admin/Views/Shared/_LayoutPage1.cshtml";
}
<h2>
Index</h2>
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript">
</script>
<div id="myForm">
<p id="pid">
</p>
</div>
<input id="BTN" type="submit" value="Button" />
<script language="javascript" type="text/javascript">
$('#BTN').click(function(){
$('#pid').load("#Url.Action("Index_partial", "Admin")");
});
</script>
Partial View
#model _1.Areas.Admin.Models.AdminModule
#using (Html.BeginForm())
{
#Html.LabelFor(i => i.MyName)
#Html.TextBoxFor(i => i.MyName)
#Html.ValidationMessageFor(i => i.MyName)
<p id="getDateTimeString">
</p>
<input type="submit" value="Click here" id="btn" />
}
<script language="javascript" type="text/javascript">
$('#btn').click(function () {
var url = '#Url.Action("Index_partialPost", "Admin")';
$.post(url, null, function (data) {
});
});
</script>
Issue is - When trying to post the partial view using jQuery-post not working and giving 404. It's working with Ajax using below mentioned code of Partial View
#model _1.Areas.Admin.Models.AdminModule
#using (Ajax.BeginForm("Index", "Admin",
new AjaxOptions { UpdateTargetId = "myForm", HttpMethod = "Post" }))
{
#Html.LabelFor(i => i.MyName)
#Html.TextBoxFor(i => i.MyName)
#Html.ValidationMessageFor(i => i.MyName)
<p id="getDateTimeString">
</p>
<input type="submit" value="Click here" id="btn" />
}
You should cancel the default action of the form by returning false from your click handler:
<script type="text/javascript">
$('#btn').click(function () {
var url = '#Url.Action("Index_partialPost", "Admin")';
$.post(url, null, function (data) {
});
return false;
});
</script>
If you don't do that, the form is submitted to the server and the browser redirects to the target url leaving you absolutely no time for your AJAX request to ever execute.
Notice that it is much better to subscribe to the .submit event of the form in order to perform the AJAX request instead of the .click event of the submit button. The reason for this is obvious: there are other means to submit a form than clicking on a submit button. For example pressing the Enter key while inside an input field. If this happens your AJAX will never execute.
So here's the correct way. Start by giving an unique id to your form:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
#Html.LabelFor(i => i.MyName)
#Html.TextBoxFor(i => i.MyName)
#Html.ValidationMessageFor(i => i.MyName)
<p id="getDateTimeString">
</p>
<input type="submit" value="Click here" id="btn" />
}
and then you could unobtrusively AJAXify this form:
<script type="text/javascript">
$('#myForm').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
}
});
return false;
});
</script>
I think you need to define the Area in the routeparameter where you do #Url.Action in your partial view:
$('#btn').click(function () {
var url = '#Url.Action("Index_partialPost", "Admin", new { area = "Admin"})';
$.post(url, null, function (data) {
});
});
Else it will be posted to your main (root) Area where you probably don't have a AdminController...
You can doublecheck the url in the JS your HTML source when the form is rendered, it sould read "/Admin/Admin/Index_partialPost" instead of just "/Admin/Index_partialPost"

Resources