How to use div by its Id in MVC Controller? - c#

I'm developing a new application in ASP.Net MVC (beginner) from old application which is in ASP.Net and have one query that How should I convert below line of code into new in MVC?
HTML:
<div runat="server" id="dvLogList"></div>
.cs:
dvLogList.InnerHtml = sb.ToString()
I need to set the StringBuilder appended string html code to as dvLogList innerhtml

You can strongly-typed your view.
As an example I have a model:
class DisplayModel
{
public string str { get; set; }
}
In my controller I will pass this model to my view:
public ActionResult Display()
{
DisplayModel model = new DisplayModel
{
str = sb.ToString()
}
return View(model);
}
The next step is to make my view strongly typed. To make this possible add this line to the top
#model DisplayModel // Most of the cases you need to include the namespace to locate the class
<div id="dvLogList">#Model.str</div> // now your model is accessible in view
In the end, why are we doing this?
This one has the advantage compared to using viewbag because there are cases that we need to postback data to our controller. The values from your view were automatically binded to your model (given that you declare the model in your action).
// model is automatically populated
public ActionResult Save(DisplayModel model)
{
}
For further knowledge, read this link I cannot spare more time to improve this answer Strongly Typed Views

In your controller, make use of ViewData (or ViewBag)
ViewData["dvLogList"] = "whatever content you want";
In your view you can call the ViewData wherever you need it:
<div id = "dvLogList" >
#(new HtmlString(ViewData["dvLogList"].ToString()))
</div>
Hope this helps.

You can do this by following way:
in your controller action that invokes this view:
public ActionResult Index()
{
ViewBag.HTMLContent = "your HTML Content";
return View();
}
In Index.cshtml view:
<div id="dvLogList">
#Html.Raw("#ViewBag.HTMLContent") /*assuming your content is HTML content not just string*/
</div>

Use below code :
//Controller Action
public ActionResult Index()
{
ViewBag.HTMLContent = "Your HTML Data";
return View();
}
//View page code
<div id="dvLogList">
#Html.Raw((String)ViewBag.HTMLContent)
</div>

Related

Partial page update ASP.NET Core MVC

In controller, method associated with page recieves ViewData from other part of the programme and displays the View like this
public IActionResult Index() {
ViewData["msg"] = Client.GetMessage();
return View();
}
How can I update page only partially if ViewData I need to display changed?
Though you didn't show the complete picture but from here I can suggest you to go for conditional razor syntax in your html.
For example:
<div>
#if(msg.Length>10){
<p>Too big message.</p>
}
else {
<p>#msg</p>
}
</div>

How to populate a Model in MVC

So I am trying to populate a model, which needs a userId. So right now, my ActionResult Index method just returns a view which prompts for the user to enter their userId. I need to grab this value and then create the viewmodel and then pass it in back to the view so that way I can do stuff like #Model.blah. I was wondering how I can do that, whether it'd be having two different action result methods, or in general how to populate models when the information you need must be queried first before constructing the viewmodel.
Here is my controller:
public ActionResult Index()
{
// Ask for UserID
return View("~/Views/FingerprintTool/Index.cshtml");
}
public ActionResult Index(int userId)
{
var response = _driver.ListFingerprints(userId);
var model = new FingerprintToolModel()
{
Fingerprints = response.Fingerprints
};
return View(model);
}
And here is my html:
model Models.Tools.FingerprintToolModel
<head>
<script type="text/javascript" src="~/Scripts/FingerprintTool.js"></script>
</head>
<body>
<h1>Fingerprint Tool</h1>
<form id="userIdForm" method="post">
Type in your UserId: <input name="userId" type="number" id="formUserId"/>
<input type="submit"/>
</form>
#if (Model != null)
{
<h1>SUCCESS</h1>
}
</body>
I also have a Javascript file that deals with the submit button be clicked and whatnot.
Here is the Js:
window.onload = function() {
$("#userIdForm")
.submit(function(e) {
e.preventDefault();
if ($("#formUserId").length == 0) {
alert("Invalid UserId");
} else {
listUserFingerprints();
}
});
}
function listUserFingerprints() {
// what to do here
}
Form:
First, update your form. You can use a simple HTML form, or the #Html.BeginForm() helper, like so:
#using Html.BeginForm()
{
#Html.AntiForgeryToken()
<label for="userId">Enter your User ID:</label>
<input type="number" name="userId" id="userId" />
<input type="submit" />
}
By default, your Html.BeginForm creates all the necessary elements and form action etc. If you prefer, you can still use standard HTML. Both do the same job.
Note the AntiForgeryToken. This is so useful when using POST form data (and even get, if you really must).
In your Controller, you can then check against this AntiForgeryToken, to protect against malicious posts or data being injected - see below.
Controller:
Create another method in your Controller, with the same name as your existing one; decorate it with the [HttpPost] attribute.
If you are using an AntiForgeryToken, you need to decorate the method with [ValidateAntiForgeryToken] also.
Like this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(int userId)
{
// MVC's DefaultModelBinder is smart enough to map your form
// post values to objects of the correct type, given the name in the form
// Get the data from your repository etc.
var model = GetUser(userId);
// Then return this model to the view:
return View(model);
}
Notice the parameter we are looking for in the method signature matches the name attribute of the input in your form.
MVC's DefaultModelBinder is able to make the connection between the two and map the value(s) of any parameters to form values.
You can also check if your model is null (for example, that userId doesn't exist) and then return an error to the page if so.
I like to use validation errors, but you can also use ViewBag or any other kind of method.
You can do a check and add an error, like this:
// Get the data from your repository etc.
var model = GetUser(userId);
if (model == null)
{
ModelState.AddModelError("", "The user ID you entered cannot be found. Please try again");
}
// Then return this model to the view:
return View(model);
This will add a "generic" model error to the view data, which you can then process in the view. More on that, below.
View:
In order to support your view displaying your model, you need to insert an #model statement at the top of your cshtml file.
Like so:
#model MyNameSpace.Models.User
This tells the view engine what Model type to expect from the Controller. In this case I have used User, but it would be whatever your class is called.
Be sure to use the fully-qualified namespace of your class in order to access it.
Then, in your HTML code, you can access the properties of your model using #Model.YourProperty.
Like this:
...
<div>#Model.Username</div>
<div>#Model.FullName</div>
<ul>
#foreach (var fingerPrint in Model.FingerPrints){
<li>#fingerPrint.WhateverProperty</li>
}
</ul>
...
As you can see, this loops through the FingerPrints (or whatever the property is called on your model object) and prints them out in a <ul>. This is to give you an idea of how to access the data from your model.
It is a good idea to create strongly-typed views like this - as this is the WHOLE idea of MVC in the first place :)
Don't forget to add an if check around the part of the page you're access the #Model data (otherwise you will get a NullReferenceException):
#if (Model != null){
<div id="modelDataInHere">
... // Display the data from your model, nice and pretty-like
</div>
}
Note the casing difference between the declaration and printing the values to the HTML output. I won't go into detail, but this is correct and necessary. Don't mix the two up.
Over to that "Validation Error" (AddModelError) we added in the Controller.
If you're using the Html.BeginForm() helper - like in the example - then you can add a Summary in the form, somewhere. When ModelState.AddModelError() is called in your controller, this populates the view data and this error can be displayed on the page.
Like so:
#using Html.BeginForm()
{
#Html.AntiForgeryToken()
// This puts any "generic" error messages at the top of the form
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
// Original form fields
<label for="userId">Enter your User ID:</label>
<input type="number" name="userId" id="userId" />
<input type="submit" />
}
No need for any Ajax or any JavaScript in here. You're simply using MVC for what it was designed in the first place.
You can use Ajax, however.
I would encourage you to read into it. There is also a similar helper: Ajax.BeginForm(), which renders the form as an Ajax one.
A bit of JS set up is required. And your controller action could return a PartialView, rather than a full-blown one.
Have a read up on using Ajax form posts here: http://eliot-jones.com/2014/09/mvc-ajax
The finished article
Time is marching on, and this post is getting longer.
But for the sake of clarity, your view and controller should look something like below. (I've stuck in a made-up class, so you can see the where the properties come from):
View
#model YourNameSpace.Models.User
... all your other code in here...
<div>
#using Html.BeginForm()
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<label for="userId">Enter your User ID:</label>
<input type="number" name="userId" id="userId" />
<input type="submit" />
}
</div>
#if (Model != null)
{
<!-- If there is a model present, display the data for it: -->
<div>
<div>#Model.Username</div>
<div>#Model.FullName</div>
<ul>
#foreach (var fingerPrint in Model.FingerPrints)
{
<li>#fingerPrint.WhateverProperty</li>
}
</ul>
</div>
}
Controller
public ActionResult Index()
{
// This is your standard "GET" request for "Index"
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(int userId)
{
// MVC's DefaultModelBinder is smart enough to map your form
// post values to objects of the correct type, given the name in the form
// Get the data from your repository etc.
var model = GetUser(userId);
if (model == null)
{
ModelState.AddModelError("", "The user ID you entered cannot be found. Please try again");
}
// Then return this model to the view:
return View(model);
}
Sample model
public class User
{
public string Username { get; set; }
public string FullName { get; set; }
public List<FingerPrint> FingerPrints { get; set; }
}
Sincerely hope this helps you, and I wish you the best in your project.
Any questions, please feel free to ask :)
Seems like you need to work with json and AJAX method:
[HttpPost]
public ActionResult BasePage(int userId)
{
// user ID is binded to userId variable, based on the input name
var model = populate(userId);
// Remember to return the model to the view
return Json(model);
}
The Javascript for calling this would be:
function listUserFingerprints() {
$.post("/FingerprintTool/BasePage", {userId: $("#formUserId").val() }, function(model) {
console.log(model); // do whatever you want with model here
}
}

Best approach to switch PartialView result that is displayed based on configuration

So right now if I want to change what partial view I display on a page based of off configuration I do the follow:
Config Item:
<add key="InstanceOwner" value="companyName" />
Call to render partial view:
<div id="" class="sidebarBox side-box3">
Html.RenderAction("ProductFeature", "Dashboard");
</div>
Controller ActionResult:
[OutputCache(Duration = 1)]
[ValidateInput(false)]
public ActionResult ProductFeature(string viewName = InstnaceOwner+"ProductFeature")
{
return PartialView(viewName);
}
I will name the partial views using a naming convention that is companyName-ProductFeature, the companies name will be variable. Doing it this way feels wrong and inefficient. I'm still really new to .NET MVC though and just want to know what the best approach to this is,Thanks!
the plan is to just change the value of the configuration key if I'm
having to change which instance (which customer) the app is being used
for
Based on that comment then it could just be as simple as reading the config value and use that to determine which view to show. You don't need to accept any parameters for the controller method.
public ActionResult ProductFeature()
{
var prefix = ConfigurationManager.AppSettings["InstanceOwner"];
return PartialView(prefix+"ProductFeature");
}
What version of MVC are you using?
If i was you, i will get all the data soon as i enter the page controller (e.g. HomeController)
public ActionResult Index()
{
var model = new SomeViewModel();
model.ProductFeature = InstnaceOwner + "ProductFeature"
return View(model);
}
Then in the View, (index.cshtml)
#Html.Partial("_ProductFeature", Model.ProductFeature)
and in the partial View (_ProductFeature.cshtml)
#model string
<span>Product Feature is #model</span>
Hope this answers your question

Call Html.RenderAction from inside HTML string

I have a ASP.NET MVC 4 application that uses database to store pages (HTML), galleries, forms etc... I want to provide users a functionality to call other controller from inside pages.
Simplified problem is how to call render action from database acquired string. Just for example I would like that string contains #Html.RenderAction("Show", "Gallery", new {id=5})
Another option I have to parse string inside a controller and render all sub calls to string before rendering this HTML.
EDIT:
The database would return something like code bellow, service layer can substitute {$gallery$} with #Html.RenderAction("Show", "Gallery", {id=5})
<div class="text">
<h1> title </h1>
<p> this is some random text {$gallery$} </p>
</div>
From your statement
Simplified problem is how to call render action from database acquired
string.
I get that you want to call an action using dynamically provided action-name and controller. If this what you want you could get it using
ViewModel
public class MyViewModel{
public string Action {get;set;}
public string ControllerName {get;set;}
}
Controller
public class MyController : Controller{
public ActionResult MyView(){
return View(new MyViewModel
{ Action ="MyPartialView" , ControllerName = "my"});
}
public ActionResult MyPartialView(){
return PartialView();
}
}
View
#model MyView
....render stuff for the view
#{
Html.RenderAction(Model.Action,Model.ControllerName);
}

sending a model in mvc3 using html.beginform

I have an HttpPost and HttpGet version of the action method Rate() :
http://pastebin.com/embed_js.php?i=6x0kTdK0
public ActionResult Rate(User user, Classified classified)
{
var model = new RatingModel
{
CurrentUser = user,
RatedClassified = classified,
};
return View(model);
}
[HttpPost]
public ActionResult Rate(RatingModel model)
{
model.RatedClassified.AddRating(model.CurrentUser, model.Rating);
return RedirectToAction("List");
}
The view that HttpGet Rate() returns:
#model WebUI.Models.RatingModel
#{
ViewBag.Title = "Rate";
}
Rate #Model.RatedClassified.Title
#using(Html.BeginForm("Rate","Classified", FormMethod.Post))
{
for (int i = 1; i < 6; i++)
{
Model.Rating = i;
<input type="submit" value="#i" model="#Model"></input>
}
}
I'm trying to find out to send a Model through the Form to the Post method, and my thinking was that the value "model" in the submit button's tag would be the parameter to do so, however null is being passed through if i breakpoint inside of the Post method. The for loop is trying to create 5 buttons to send the proper rating.
Thanks
Them model binding works on the name attribute as #Ragesh suggested you need to specify the name attributes matching the RatingModel properties in the view. Also note that the submit button values dont get posted to the server, there are hacks through which you can achieve that, one way is to include a hidden field.
Also in your provided code the loop runs six times and at the end Model.Rating will be equal to 5 always... what are you trying to achieve?. Say for example you have a model like
public class MyRating{
public string foo{get;set;}
}
in your view
#using(Html.BeginForm("Rate","Classified", FormMethod.Post))
#Html.TextBoxFor(x=>x.foo) //use html helpers to render the markup
<input type="submit" value="Submit"/>
}
now your controller will look like
[HttpPost]
public ActionResult Rate(MyRating model)
{
model.foo // will have what ever you supplied in the view
//return RedirectToAction("List");
}
hope you will get the idea
I think there are two things you need to fix:
The input tag needs a name attribute
The name attribute should be set to model.Rating

Categories

Resources