MVC 5 PartialVIew is loading in Different Page - c#

Overview:
I am essentially building a single page application. Three inputs and two tables that load based on the inputs' data.
Each table is set to a tab and each tab has a button to load their respective table's data. One table is set in a partial view. I'm trying this out to see if it works so I can set both of the tables to a partial view.
Problem:
The partialview is loading the table into a new window when I click the submit button.
Example:
So, upon loading the web application, for example, 'http://localhost:30000/CommissionDatas/' the Index page loads the page and the empty tables just fine.
I am using a ViewModel because each table uses a different model and I will get an error about the Partial view table having a different data model.
Once I click the button "gpmbutton", for the partial view table, the buttion uses the 'formmethod' attribute to call actionresult method '_TrueUp' and it will retrieve the data and return the data model to the partial view. But, the partial view's table and it's data ends up posting the to 'http://localhost:30000/CommissionDatas/_TrueUp', which is a completely new page.
I have already tried changing the actionresult method type to PartialViewResult and changing the return type from 'PartialView()' to a 'View' in the controller and that still did not work. I've also tried using #Partial in the index page as well as #RenderPartial for the partial view and I get the same result.
Also, both the 'Index' and the '_TrueUp' PartialView page are in the same folder under 'CommissionDatas' in the views folder.
Please HELP!
P.S. I removed the code that is not essential to the problem as the data is sensitive.
Index.cshtml
-------------------------------------------------------------
#model CommissionReport.Models.ViewModels.CommissionViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="submit" ID="commissionbutton"
formaction="ReturnCommissionData"
formmethod="post"
/>
#if (Model != null)
{
<table id="mainTable" class="ui striped selectable table">
<thead>
<tr>
</tr>
</thead>
<tbody>
#foreach (var item in Model.CommissionData)
{
<tr>
</tr>
}
</tbody>
</table>
}
<input type="submit" class="btn btn-primary" ID="gpmbutton"
formaction="_TrueUp" formmethod="post"
/>
<div>
#if (Model != null)
{
Html.RenderPartial("_TrueUp");
}
</div>
</body>
</html>
This is the Partial View
_TrueUp.cshtml
----------------------------------------------------------------------------
#model CommissionReport.Models.ViewModels.CommissionViewModel
#{
Layout = null;
var trueupmodel = Model.TrueUp;
}
#if (Model != null)
{
<table id="mainTable" class="ui striped selectable table">
<thead>
<tr>
</tr>
</thead>
<tbody>
#foreach (var item in Model.TrueUp)
{
<tr>
</tr>
}
</tbody>
</table>
}
This is the Controller.
private CommissionViewModel vm = new CommissionViewModel();
[HttpPost]
public ActionResult ReturnCommissionData(FormReturn form)
{
//Code to return data here
vm.CommissionData = db.CommissionDatas.ToList();
return View("Index", vm);
}
<HttpPost>
public ActionResult _TrueUp(FormReturn form)
{
//Code For Data to be returned here
vm.TrueUp = model;
return PartialView("_TrueUp", vm);
}

Please try #Html.Action("yourAction", "yourController") instead of #Html.RenderPartial("_TrueUp").
For further information visit:
How can I use Html.Action?
MSDN
EDIT:
Use: #Html.Partial("partialViewName", partialViewModel) partialViewModel is optional.
In your case: #Html.Partial("_TrueUp").

Related

In an ASP.NET Core MVC Razor view, issue related to #model IEnumerable<Namespace.Model> Vs #model<Namespace.Model>

In an ASP.NET Core MVC Razor view, I have 2 forms. One input form is used to populate 2 dropdown lists as ajax modelpopup and saving values in database. Another form is used to display the related values as datatable in same view.
When I try to populate data table by #foreach(var item in Model) loop by declaring #model IEnumerable<Namespace.Model> in view, it works fine for assigning value to datatable controls.
But other form having dropdownlist shows error. Not able to declare asp-for for select control.
<div class="form-group"> #{var Jsonlist = new electList((System.Collections.IEnumerable)ViewData["JsonPropVD"], "Value", "Key");}
<select asp-items="Jsonlist" asp-for="ClientCatalog" class="form-control"></select>
</div>
public void GetJsonProperties()
{
PropertyInfo[] propertyInfosSM = typeof(SMJsonModel).GetProperties();
if (propertyInfosSM != null)
{
Dictionary<string, object> Jsondictresults = new Dictionary<string, object>();
foreach (PropertyInfo propertyInfoJson in propertyInfosSM)
{
Jsondictresults.Add(propertyInfoJson.Name, propertyInfoJson.Name);
}
ViewBag.VBJsonProp = Jsondictresults.Keys;
ViewData["JsonPropVD"] = Jsondictresults;
}
}
When I change from #model IEnumerable<Namespace.Model> to #model<Namespace.Model>, I am able to access dropdownlist in the form but #foreach(var item in Model) shows an error. So I need to populate with viewbag.
<tbody>
#foreach (K360Master Mappeddata in ViewBag.K360MappedData)
{
<tr>
<td>#Mappeddata.Id</td>
<td>#Mappeddata.ClientCatalog</td>
<td>#Mappeddata.K360catalog</td>
<td>
<button id="btnDelete" asp-action="DeletePost" asp-route-Id="#Mappeddata.Id" class="btn btn-danger mr-3">Delete</button>
</td>
</tr>
}
</tbody>
It’s not advisable to use viewbag and viewdata. Please guide me how to achieve this by using strongly typed view for the above requirement.
You can remove the asp-for tag helper in the select tag, and manually set its id and name
<select asp-items="Jsonlist" id="ClientCatalog" name="ClientCatalog" class="form-control"></select>

partial view ASP MVC 5 C#: how to get part of the table using partial view?

I'm trying to make a table using partial view from another view.
the content of the view I want to desplay:
#model Agro1.ModelView.MessageViewModel
#using Agro1.Models
<span style="color:darkgreen">Messages</span>
<br />
<table>
<tr>
<td>Subject</td>
<td>Content</td>
<td>Farmer Email</td>
</tr>
#{
foreach (Message obj in Model.messages)
{
<tr>
<td>#obj.Subject</td>
<td>#obj.Content</td>
<td>#obj.FarmerEmail</td>
</tr>
}
}
</table>
in another view I want to desplay only the 5 first rows of this table.
now my code in the view looks like this:
#Html.Partial("DisplyaMessages",Model)
and it shows the full table.
how can I desplay only the 5 first rows?
t
You could use linq syntax .take(5) either in the controller action or in the razor.
Your razor code would look like this:
#{
foreach (Message obj in Model.messages.take(5))
{
<tr>
<td>#obj.Subject</td>
<td>#obj.Content</td>
<td>#obj.FarmerEmail</td>
</tr>
}
You should add a new property into the model with the max rows to display.
After that you can check this property during the foreach.
#model Agro1.ModelView.MessageViewModel
#using Agro1.Models
<span style="color:darkgreen">Messages</span>
<br />
<table>
<tr>
<td>Subject</td>
<td>Content</td>
<td>Farmer Email</td>
</tr>
#{
var x = 0;
foreach (Message obj in Model.messages)
{
if (Model.MaxRows > 0 && x > Model.MaxRows) break;
<tr>
<td>#obj.Subject</td>
<td>#obj.Content</td>
<td>#obj.FarmerEmail</td>
</tr>
x++;
}
}
</table>
You can call the partial creating a new model like this:
#Html.Partial("DisplyaMessages", new MessageViewModel { MaxRows = 5, messages = Model.messages})

Partial View List returns null when saving the model

I pass a List to a partial view and it works fine, it shows all the data but when I save the Model, the List returns null, what am I missing?
Dont pay attention to the objects, I wrote fake ones for the example.
This the cshtml:
#model ViewModels.StudentVM
#using (Html.BeginForm("SaveStudent", "StudentsView", FormMethod.Post}))
{
#Html.AntiForgeryToken();
<div class="row">
<span>Student name:</span>
#Html.TextBoxFor(s => s.Name)
</div>
<div>
#Html.Partial("StudentsList", Model.Students)
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn">
</div>
}
When loading the view I get all the students to the View Model:
vm.Students = await _studentController.GetAllStudents(); // returned 20 Students.
The partial view:
#model IEnumerable<Entities.Students>
<table class="table-bordered">
#foreach (var item in Model)
{
<tr>
<td>
#Html.CheckBoxFor(modelItem => item.IsSelected)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
}
</table>
I would like to get all selected students, so lets say I will select 3 students.
And then click on the save button. Result: the Model.Students is null although it I selected 3 students. How can I get those students?
Your current code of partial view has only the Call to DisplayNameFor helper method which will only render the display name as a label. If you want to submit the data of each item, you need to generate input form fields with matching names with your view model property structure.
Assuming your StudentVM has a Students collection of type IEnumerable<Students>
If your HttpPost action method's parameter is of type StudentVm, you need to make sure that your partial view is generating the input form fields with name like 'Students[0].Name, 'Students[1].Name etc. You can use the Html.TextBox helper method and specify this custom names
#model IEnumerable<Students>
<table class="table-bordered">
#{
var counter = 0;
}
#foreach (var student in Model)
{
<tr>
<th>Name</th>
<td>#Html.TextBox("Students[" + counter + "].Name", student.Name)</td>
</tr>
counter++;
}
</table>
If you are simply displaying the names of existing students, you do not need the text fields, you can simply display those inside the loop. In that case, when form submits,why do you worry about the Students collection being null ? You are trying to save a new Student which will be in .Name property. So if you need the existing students again (but why ? ), you can call the GetAllStudents method.
maybe you used 2 Different model in view ......
you can use 2 model in 1 viewmodel
It is not necessary partial view
ViewModels.StudentVM != IEnumerable<Entities.Students>
you can all data (many model) passed in 1 view model
:
var vm = new TestViewModel();
vm.one = db.one.tolist();
vm.two = db.two.tolist();

Pass Html String from Controller to View ASP.Net MVC

Which is the best way to pass the Html String block from Controller to View in MVC. I want it display that html block at the page load. Thank you. It can be any Html,
e.g
<table style="width:300px">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
I want to pass this as a string from controller to View. where it will be displayed as an html.
Thank you.
In your controller action :
ViewBag.HtmlStr = "<table style=\"width:300px\"><tr><td>Jill</td><td>Smith</td> <td>50</td></tr><tr><td>Eve</td><td>Jackson</td><td>94</td></tr></table>";
Your view :
#Html.Raw(ViewBag.HtmlStr)
You can assign the html in controller to ViewBag and access the ViewBag in View to get the value that is the html
Controller
ViewBag.YourHTML = htmlString;
View
<div> #ViewBag.YourHTML </div>
Its better to not to pass the html from controller to View rather pass the object or collection of object to View (strongly typed view) and render html in View as it is responsibility of View
Controller
public ActionResult YourView()
{
//YourCode
return View(entities.yourCollection.ToList());
}
Veiw
<table style="width:300px">
foreach (var yourObject in Model)
{
<tr>
<td>#yourObject.FirstName</td>
<td>#yourObject.LasttName</td>
<td>#yourObject.Amount</td>
</tr>
}
</table>
Best approach will be to create a partial view and append the html returned by it in your parent view inside some container div.
In your main view do like this:
<div>
#{
Html.RenderAction("youraction","yourcontroller")
}
</div>
in your action do this:
public ActionResult youraction()
{
return View();
}
and your partial view:
#{
Layout = null;
}
<table style="width:300px">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Controller
ViewBag.HTMLData = HttpUtility.HtmlEncode(htmlString);
View
#HttpUtility.HtmlEncode(ViewBag.HTMLData)
You can use ViewBag.YourField or ViewData["YourStringName"] and for retreiving it in your View. Just place it where you want preceded by # like this #ViewBag.YourField or #ViewData["YourStringName"].

unable to render partial view in asp.net mvc using ajax?

Problem is : I do have Index.cshtml as
#{
ViewBag.Title = "Search";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="#Url.Content("../../Scripts/jquery.unobtrusive-ajax.min.js") type="text/javascript"></script>
<h2>Answer's are </h2>
<div id="result">
#Ajax.ActionLink("Search Wiki",
"WikiAns",
new AjaxOptions{
UpdateTargetId = "result",
InsertionMode=InsertionMode.Replace,
HttpMethod="GET",
LoadingElementId="progress"
})
</div>
<div id="progress" style="display: none">
<img src="#Url.Content("../../Content/Images/ajax-loader.gif")" alt="loader" />
</div>
Now i do have partial view model _WikiAns:
#model IEnumerable<Questions.Models.WikiAnsClass>
<h2>Our Links</h2>
<table>
#foreach (var item in Model) {
<tr>
<td>
#item.content
</td>
</tr>
}
</table>
Now using above i want is that...on clicking Search Wiki action link, id="result" get all partial view rendered in it. But its not happening. Instead of its going to a page "localhost:80/Search/WikiAns" and showing the result there. but i want to it to stay at localhost:80/Search and replace its "result" id. but its not working this way.
Here is my action called WikiAns
public ActionResult WikiAns()
{
//Code to follow...
var wikians = //code to follow
return PartialView("_wikiAns", wikians);
}
What's the problem ?
Also how can i implement this Ajax GIF loader...i mean showing it while action gets executed. ?
Please suggest
Thanks
#Pbirkoff may be right about this but you can go through my post of very easy to implement demo of your scenario and build it up from there.
http://mazharkaunain.blogspot.com/2011/05/aspnet-mvc-razor-render-partial-view.html
http://mazharkaunain.blogspot.com/2011/04/aspnet-mvc-render-partial-view-using.html
You need to include Microsoft Ajax scripts at your page or layout.

Categories

Resources