Getting error in mvc4 - asp.net

Error:-
Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.
My Main page View is this
{
ViewBag.Title = "Start";
}
<h2>Start</h2>
<script type="text/javascript">
$(document).ready(function () {
$("#test1").click(function (e) {
$("#firstpartialview").css("display", "none");
$("#secondpatialview").css("display", "none");
$("#firstpartialview").css("display", "block");
});
$("#test2").click(function (e) {
$("#firstpartialview").css("display", "none");
$("#secondpatialview").css("display", "none");
$("#secondpatialview").css("display", "block");
});
});
</script>
<a id="test1"></a>
<a id="test2"></a>
<div id="firstpartialview">#Html.Action("FirstView", "Home") </div>
<div id="secondpatialview">#Html.Action("SecondView", "Home") </div>
My controller is this:-
public ActionResult Start()
{
return View();
}
public ActionResult FirstView()
{
ModelA objA = new ModelA();
return PartialView(objA);
}
public ActionResult SecondView()
{
ModelB objB = new ModelB();
return PartialView(objB);
}
My Partial View is this
_partialA.cshtml
#model demo3.Models.ModelA
#{
ViewBag.Title = "_partialA";
}
<h2>_partialA</h2>
<div>#Html.EditorFor(m => m.EmployeeId) </div>
<div>#Html.EditorFor(m => m.EmployeeName)
and another partial view is this
_partialB.cs.html
#model demo3.Models.ModelB
#{
ViewBag.Title = "_partialB";
}
<h2>_partialB</h2>
<div>#Html.EditorFor(m => m.Comapny) </div>
<div>#Html.EditorFor(m => m.FisacalYear) </div>
Please help me to solve the error..on browser this error is coming
The partial view 'FirstView' was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/FirstView.aspx
~/Views/Home/FirstView.ascx
~/Views/Shared/FirstView.aspx
~/Views/Shared/FirstView.ascx
~/Views/Home/FirstView.cshtml
~/Views/Home/FirstView.vbhtml
~/Views/Shared/FirstView.cshtml
~/Views/Shared/FirstView.vbhtml

The error means that mvc is trying to load a file (by default, if you haven't specified the view file name, it checks by Action name which in this case, is FirstView), but it can't find it.
You can specify the view file name in your return statement:
return PartialView(string "View", object model)
This can be used like so (assuming _partialA is your view's cshtml filename):
return PartialView("_partialA", objA);

The error is quite specific. This line is causing your error:
<div id="firstpartialview">#Html.Action("FirstView", "Home") </div>
It can't find the view FirstView. You need to place the view in one of the locations that the error message tells you or change where the view engine searches for your views.

Related

how to get Partial Views in mvc 5 posted data?

Iam Asp.net Webform Developer and are trying to learn .net MVC 5.
I know how to make partial view with only static html tags in MVC 5.
But can i in a MVC partial View also have a form with textboxes and a submit buttion ?
If yes, so where do i write Postback function for this partial View for get its posted values ,in which controller ?
Yes, You can have text boxes and a submit button in partial view as well.
Lets say for example you have a product application, and your main page (View) is displaying all the product available.
so in order to show the product you need to pass a model
#model IList<xyzRetailer.ViewModels.ProductViewModel>
#{
ViewData["Title"] = "Home Page";
}
and you can read the value like:
<div class="col-md-3">
<h2>Product Categories</h2>
<ul>
#foreach (var item in Model.Select(a=>a.Category).Distinct())
{
<li>#item</li>
}
</ul>
</div>
Now to your question if you want to have a a partial view with different view model you can go with tuple or you can have a new object created just for partial view while calling it like below
#Html.Partial("_AddProduct", new yzRetailer.ViewModels.ProductViewModel())
and your partial view will be something like below:
#model xyzRetailer.ViewModels.ProductViewModel
#using (Html.BeginForm("Create", "Home", FormMethod.Post))
{
<div class="input-group">
#Html.TextBoxFor(model => model.Id, new { #class = "hidden" })
#Html.TextBoxFor(model => model.Category, new { #class = "form-control" })
</div><input type="submit" value="Save" class="btn btn-primary btn-block" />
}
And the controller code should go Home-> Create that you have mentioned in #Html.BeginForm.
public async Task<IActionResult> Create(ProductViewModel product)
{
if (!ModelState.IsValid)
{
return this.BadRequest(ModelState);
}
if (string.IsNullOrEmpty(product.Id))
{
var result = await _catelogueManager.AddAsync(product);
}
else
{
var result = await _catelogueManager.UpdateAsync(product.Id, product);
}
var products = await _catelogueManager.GetAllAsync();
return View("Index", products);
}

ASP.NET MVC 3: jQuery $.get(url, data, callback, type)

I am attempting to dynamically update a select list based on a selection in another select list. The jQuery code
<script type="text/javascript">
// Respond to Category selection
$('#selectCategory').change(function () {
// Ajax call to 'Specialties' action method with parameter searchType
$.get('#Url.Action("Products", "Product")',
{ "parameter1": $(this).val(), "parameter2": null },
function (data) {
$('#products').html(data);
});
});
</script>
the view
<div id="products">
#Html.Partial("_Products")
</div>
the partial view
#model MyMVC3App.Models.MyViewModel
<select mid="productSelect" name="#ClarusConstants.PropertyNames.Specialty" >
<option value="0">#Resources.LabelText_SelectASpecialty</option>
foreach (Product p in Model.Products)
{
<option value="#Product.ID" name="#product.Description</option>
}
</select>
the action method
public ActionResult Specialties(string parameter1, string parameter2)
{
List<Product> products = myDB.Products.Where(p => p.Category == parameter1).ToList();
ViewModel myViewModel = new ViewModel();
viewModel.Products = products;
if (Request.IsAjaxRequest())
{
return PartialView("_Products", myViewModel);
}
else
{
return View(myViewModel);
}
}
The callback is hitting the right action method and the ajax request is being detected. Unfortunately the content (InnnerHTML) of the products div is not being replaced so it is all for nothing.
Thank you in advance for your help.

Making Partial View Reusable

Say I have a partial view that renders a dropdown list of Applications. When selecting an item in the dropdown it renders another partial view.
This dropdown list exists in a few places in the application but on each page a different partial view needs to be rendered when selecting an application. Is there an easy way to make the dropdown reusable? ie I need to set a different data_url depending on which page the partial view is rendered.
Partial View:
<script type="text/javascript">
$(function () {
$('#ApplicationsDropdownList').change(function () {
var url = $(this).data('url');
var applicationId = $(this).val();
$('#RolesForApplication').load(url, { applicationId: applicationId})
});
});
</script>
<div>
<label for='ApplicationsDropdownList'>Application:</label>
#Html.DropDownListFor(
x => x.SelectedApplicationId,
new SelectList(Model.Applications, "Value", "Text"),
"-- Select Application --",
new
{
id = "ApplicationsDropdownList",
data_url = Url.Action("ViewRolesTableForApplication", "Index")
}
)
</div>
Controller:
public ActionResult ViewRolesTableForApplication(string applicationId)
{
...
return View("_RolesTableForApplicationPartial");
}
You could add a string property containing the data_url to the model that you use for your partial view.
So in addition to the Model containing Applications it will have public string DataUrl { get; set; } as well.

mvc3 partial view error

I want to make a form for entering customer data. It consists of several text boxes and a combobox. And it is the whole problem lies in this combobox. When I trying to render this partialview , gets error: "Object reference not set to an instance of an object."
This is partialview controller code
public PartialViewResult GetStates()
{
var states = from s in conn.order_data select s.state;
return PartialView(states.ToList());
}
GetStates partialview
#model IEnumerable<bookstore.state>
#foreach (var item in Model) {
<select>
<option>#item.STATE_Name</option>
</select>
}
part of main view
<div class="editor-field">
#{Html.RenderPartial("GetStates");}
</div>
Please, help
Unless you are loading the view dynamically (in which case you could do it with jquery get)
here is how you could do it
Controller:
public ActionMethod MainView()
{
var model = new myMainModel { States = from s in conn.order_data select s.state };
return View()
}
Main View:
#Html.Partial("MyPartialViewName", Model.States);
Try this:
if(states != null)
{
return PartialView(states.ToList());
}
return PartialView();

MVC 1.0 Ajax.BeginForm() submit inside an Html.BeginForm()

I have a View for creating a new account in my application. This view starts with Html.BeginForm() and hits the right controller (Create) no problems.
I decided to add an Ajax.BeginForm() so that I could make sure an account with the same name doesn't already exist in my application.
When I click the submit using either button it goes to the same controller (Create). To try and differentiate which submit button was clicked, I put in a check to see if the request is Ajax then try to run a different code path. But Request.IsAjaxRequest() doesn't fire. What is my best bet to implement this functionality in an existing form with MS Ajax?
<% using (Html.BeginForm()) {%>
..............
<% using(Ajax.BeginForm("Echo",
new AjaxOptions() { UpdateTargetId = "EchoTarget" }))
{ %>
Echo the following text:
<%=Html.TextBox("echo", null, new { size = 40 })%>
<input type="submit" value="Echo" />
<% } %>
<div id="EchoTarget">
controller code:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(User newUser)
{
if (Request.IsAjaxRequest())
{
return Content("*you hit the ajax button");
}
else
{ //regular create code here.....
}
</div>
If you insist on multiple form usage..use Javascript in a some function like this
<SCRIPT>
function InnerFormSubmitter(dataForm, actionForm) {
actionForm.innerHTML = dataForm.innerHTML;
actionForm.submit();
}
</SCRIPT>
<form name="yourButton" action="ValidateSomething" method="post"></form>
<form name="mainForm" action="SavedData" method="post">
<input type="textbox" name="text1">
<input type="textbox" name="text2">
<button name="validateUserButton" id="FormButton" onChange=
"InnerFormSubmitter (this.form, document.getElementById('yourButton'))">
</button>
</form>
Hope this helps!
Addendum on jQuery usage for your scenario:
Since you wanted a link:
Check Availability
function isValidUser(userId) {
var url = "<CONTROLLER>/<ACTION>/" + userId;
$.post(url, function(data) {
if (data) {
// callback to show valid user
} else {
// callback to show error/permission
}
});
}
And you controller should have:
[AcceptVerbs("POST")]
public bool IsValidUser(int id) {
// check availability
bool allow = CheckUser();
// if allow then insert
if (allow) {
//insert user
return true;
} else {
return false;
}
}
Further Update on jQuery:
Instead of
document.getElementById('UserIdent').value
you can use
$('#UserIdent').val();
Update on JSON usage
The JsonResult class should be used in the Controller and $.getJson function in the View.
$(function() {
$('#yourLinkOrButton').click(function() {
$.getJSON("<CONTROLLER>/GetUserAvailability/", null, function(data) {
$("#yourDivorLablel").<yourFunctionToUpdateDiv>(data);
});
});
public JsonResult GetUserAvailability()
{
//do all validation and retrieval
//return JsonResult type
}
You cannot nest forms, ever, in any HTML page, no matter how you generate the form. It isn't valid HTML, and browsers may not handle it properly. You must make the forms siblings rather than children.

Resources