Shared partial view - asp.net-mvc

What would be the best way to display on home page (HomeController, view Index) two last news from other model (News)?
I've created partial view in shared views directory, there is how it looks like:
#model IEnumerable<MyApp.Models.News>
#foreach (var item in Model.Where(x => x.IsActive ==
true).OrderByDescending(x => x.DateCreated).Take(2)) {
<li>
#Html.ActionLink(item.DateCreated.ToString(), "Details", "News", new { id = item.NewsId})
<p>#item.Content</p>
</li>
}
but this way I'm getting error:
An exception of type 'System.ArgumentNullException' occurred in
System.Core.dll but was not handled in user code
Model is not null, there are exactly two "active" records in my db, index file for this model is also correct, but I don't have any idea how to render this partial to my index homepage... (now I have in Index.cshtml view for HomeController #Html.Partial("_LatestNews"))
Thanks for advance for any help.

You'd need to pass the model into the partial, like such;
#Html.Partial("_LatestNews", Model.News))

Your partial view is expecting IEnumerable which you missed to pass, it should have something like this.
#Html.Partial("_LatestNews", new IEnumerable<MyApp.Models.News>)
However, I would do rather following in this case.
Layout View Page
Latest News
<script>
$(function () {
$("#content").html("Loading...");
//Use setTimeout if you want to keep update or call LoadPartialView() directly.
setTimeout(function () { LoadPartialView(); }, 5000);
});
function LoadPartialView() {
$.ajax({
type: "GET",
url: '#Url.Action("GetNews", "Home")',
dataType: "html",
success: function (data) {
$("#content").empty();
$("#content").html(data);
$("#content").fadeIn('slow');
},
error: function (data) {
$("#content").empty();
}
});
};
</script>
Controller
[HttpPost]
public ActionResult GetNews()
{
List<MyApp.Models.News> model = db.GetNews();
return PartialView("_LatestNews", model);
}

Related

Pass value from anchor to controller

How can I pass the value of name.report to the controller withoout passing it through a URL, this is in a side bar. I'm sorry if this is a really simple question, but I have searched quite a lot and couldn't find a solution
#foreach (var name in Model.namesReport)
{
<li href="#" class=""><a class="menu_name"> #name.ReportName</a>
}
Controller
[HttpPost]
public ActionResult test(int? id)
{
return null;
}
Ajax call
$("getReport".click(function() {
$ajax({
url: '/Home/test',
type:'POST',
datatype: 'json',
data: {id:"test"}
});
});

How to pass an actionlink's results to a partialview placeholder?

Okay, so in my page I have a list of links:
#foreach (var item in Model)
{
#Html.ActionLink(item.Name, "Recruitments", new { Id = item.Id })
<br />
}
And what I want is for the partialview to return somewhere else on the page, in a placeholder I've set aside.
Is this possible? Or do I have to use jquery ajax calls instead somewhere?
you can #Ajax.ActionLink in asp.net mvc, it has different overloads you can use according to your requirements here is the code:
#Ajax.ActionLink("ActionName", // action name
"Recruitments", //controller name
new { Id = item.Id }, // route values
new AjaxOptions { HttpMethod = "GET", //HttpMethod Get or Post
InsertionMode = InsertionMode.Replace, // Replace content of container
UpdateTargetId = "Container", // id of element in which partial view will load
OnComplete = "Completed();" }) // js function to be executed when ajax call complete
<div id="Container">
</div>
<script>
function Completed()
{
alert("completed");
}
</script>
I did had a problem with partial for your problem post some code so I understand your problem.
Either you should use a razor helper, either you simply use jquery to manipulate the dom.
note that jquery is pretty simple
$("#selectorOnYourPlaceHolder").html($("#selectorOnYourLinks").html());
$("#selectorOnYourLinks").html("")
You want to do this with Ajax:
$.ajax({
type: "GET", url: "somePageOrHandler.aspx", data: "var1=4343&var2=hello",
success: function(data)
{
$('#someDivInPlaceHolder').html( data);
}
});

call dropdownlist selected value as #html.action route value

How to call dropdownlist selected value as #html.action route value.
I am using following code in my MVC3 razor. I have to dynamically call 'eventid' as dropdownlist selected value.
#Html.Action("FirmPassForum", "Conference", new { eventId = 69 })
You can't do that, because the Html.Action helper renders at the server, whereas the dropdown selection could change on the client. One possibility is to use an AJAX call. So basically you could subscribe to the .change() event of the dropdown and send an AJAX call to some controller action that will return a partial view and update the DOM.
Start by placing this in a container:
<div id="container">
#Html.Action("FirmPassForum", "Conference", new { eventId = 69 })
</div>
and then:
<script type="text/javascript">
$(function() {
$('#id-of-your-dropdown').change(function() {
var eventId = $(this).val();
$.ajax({
url: '#Url.Action("FirmPassForum", "Conference")',
type: 'GET',
data: { eventId: eventId },
cache: false,
success: function(result) {
$('#container').html(result);
}
});
});
});
</script>
Fr this to work your FirmPassForum action should not be decorated with the [ChildActionOnly] attribute:
public ActionResult FirmPassForum(int eventId)
{
MyViewModel model = ...
return PartialView(model);
}
You can use this also
`//var url = '#Url.Action("ActionName", "Controller")';
$.post("/Controller/ActionName?para1=" + data, function (result) {
$("#" + data).html(result);
............. Your code
});`

Can you just update a partial view instead of full page post?

Is there a way to submit a partial view form in asp.net mvc without reloading the parent page, but reloading the partial view only to its new state? Similar to how knockout.js updates using data-bind.
My data table renders with a variable number of columns/names so I don't think knockout.js is an option for this one, so I am trying to use a partial view instead.
Not without jQuery.
What you would have to do is put your Partial in a div, something like:
<div id="partial">
#Html.Partial("YourPartial")
</div>
Then, to update (for example clicking a button with the id button), you could do:
$("#button").click(function () {
$.ajax({
url: "YourController/GetData",
type: "get",
data: $("form").serialize(), //if you need to post Model data, use this
success: function (result) {
$("#partial").html(result);
}
});
})
Then your action would look something like:
public ActionResult GetData(YourModel model) //that's if you need the model
{
//do whatever
return View(model);
}
Actually, if your Partial has a child action method, you can post (or even use an anchor link) directly to the child action and get an Ajax-like affect. We do this in several Views.
The syntax is
#Html.Action("MyPartial")
The Child Action is
public ActionResult MyPartial()
{
return PartialView(Model);
}
If your form posts to the child action
#using (Html.BeginForm("MyPartial"))
{
    ...
}
The Partial View will be updated with the partial view returned from the child action.
Jquery is still a legitimate way to update a partial. But technically, the answer to your question is YES.
As normal what I find when looking for things like this is people give too limited information so I will attempt to help here. The key is to set up a div with an ID you can append the return html to. Also when hitting your controller make sure it returns the partial. There are some potential problems with this method but on a good day it should work.
<div id="CategoryList" class="widget">
#{
Html.RenderPartial("WidgetCategories.cshtml");
}
</div>
function DeleteCategory(CategoryID) {
$.get('/Dashboard/DeleteWidgetCategory?CategoryID=' + CategoryID,
function (data) {
if (data == "No") {
alert('The Category has report widgets assigned to it and cannot be deleted.');
}
else {
$('#CategoryList').html(data);
}
}
);
}
[HttpGet("DeleteWidgetCategory")]
[HttpPost("DeleteWidgetCategory")]
public IActionResult DeleteWidgetCategory(string CategoryID)
{
string Deleted = CategoryModel.DeleteCategory(CategoryID);
if (Deleted == "Yes")
{
return PartialView("WidgetCategories");
}
else
{
return this.Json("No");
}
}
I would use the Ajax Form helper for such scenarios using a partial view and #html.RenderPartial("partialName")
partial helpers
In your Main View
<div id=SearchResult>
#Html.Partial("_NameOfPartialView", Model)
</div>
<input type="button" id="btnSubmit" value="Submit">
In your Javascript file
$('#btnSubmit').click(function () {
GetData(Id);
});
function GetData(Id){
$.ajax({
url: "/Home/GetEmployee/",
type: "get",
data: { Id:Id },
success: function (result) {
$('#SearchResult').html(result);
}
});
}
In your Home Controller
public ActionResult GetEmployee(int Id)
{
var employee= context.Employee.Where(x=> x.EmployeeId == Id)
return this.PartialView("_NameOfPartialView", employee);
}

How to Pass textbox value using #html.actionlink in asp.net mvc 3

How to Pass value from text using #html.actionlink in asp.net mvc3 ?
None of the answers here really work. The accepted answer doesn't refresh the page as a normal action link would; the rest simply don't work at all or want you to abandon your question as stated and quit using ActionLink.
MVC3/4
You can use the htmlAttributes of the ActionLink method to do what you want:
Html.ActionLink("My Link Title", "MyAction", "MyController", null, new { onclick = "this.href += '&myRouteValueName=' + document.getElementById('myHtmlInputElementId').value;" })
MVC5
The following error has been reported, but I have not verified it:
A potentially dangerous Request.Path value was detected
Rather than passing your value using #Html.actionlink, try jquery to pass your textbox value to the controller as:
$(function () {
$('form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: { search: $('#textboxid').val()},
success: function (result) {
$('#mydiv').html(result);
}
});
return false;
});
});
This code will post your textbox value to the controller and returns the output result which will be loaded in the div "mydiv".
to pass data from the client to the server you could use a html form:
#using (Html.BeginForm(actionName,controllerName)) {
<input type="text" name="myText"/>
<input type="submit" value="Check your value!">
}
be sure to catch your myText variable inside your controller's method
you can use this code (YourValue = TextBox.Text)
Html.ActionLink("Test", new { controller = "YourController", action = "YourAction", new { id = YourValue }, null );
public class YourController : Controller
{
public ActionResult YourAction(int id)
{
return View("here your value", id);
}
}

Resources