Can anyone tell how to write you own method and call it view or simply write "Hello world" in the following manner? This is what I tried to write on my
Index.cshtml:
<h1>
Hello,
<span>
#{ HttpContext.Current.Response.Write("World!"); }
</span>
</h1>
but it is not working? Thanks for any help :)
Response.Write is use for write string content to the responce,
If you want to bind your test to the view than you can create a model for the view and initialize from controller and pass it to the view see below example,
Here my model is type of string, you can create your complax model if thare are more than one property
Controller:
public ActionResult Index()
{
return View("index","World!");
}
View:
#model string
<h1>
Hello,
<span>
#Model
</span>
</h1>
Related
I have a list view like
#model IEnumerable<EmpDetailsRazor.Models.EmpDetails>
#{
ViewBag.Title = "Employee Details";
}
<h2>Index</h2>
**#Html.Partial("_Create", Model);**
<p>
#Html.ActionLink("CREATE NEW","Create")
</p>
list view here
and I have created a partial view with create
template with the same model I
am using in list and I want to call partial view like
#Html.Partial("_Create", Model);
as it required model like
EmpDetailsRazor.Models.EmpDetails rather than
IEnumerable<EmpDetailsRazor.Models.EmpDetails>
how to do this?
You can call the Partial using
#Html.Partial("_Create", Model.FirstOrDefault())
Or if you know there always is at least one item, and you want to make that explicit:
#Html.Partial("_Create", Model.First())
Note that you may need to add #using System.Linq on top to make this work.
In my ASP.NET MVC (5.2) project, I have a page called register.cshtml. It doesn't include any forms or anything, just plain divs.
Inside one of the divs, I'm rendering a partial:
#Html.Partial("~/Views/Users/_x.cshtml").
Inside _x.cshtml I have a form:
#using (Html.BeginForm("/users/x"))
{
...
}
When I go to my register page, I expect my form to be rendered as:
<form action="/users/x" method="post"> ... </form>
But instead, I'm getting this:
<form action="/users/register?Length=23" method="post" novalidate="novalidate"> ... </form>
What is length=23, why is there a novalidate attribute added, and why is it posting to an incorrect path?
Why is my form not rendering properly?
If your wanting to post to a method named x in usersController, then it needs to be
#using (Html.BeginForm("x", "users"))
{
....
}
Note that your currently using the overload that accepts object routeValues and because its a string, the method generated a route value for Length because that's the only property of string (the /users/register is because that the method that generated the main view)
From your code
Html.BeginForm("/users/x")
i understand that users your controller and x is a method. So you can do in this way-
#using (Html.BeginForm("x", "users", FormMethod.Post, new { id = "YourFormID"}))
{
}
#using (Html.BeginForm("action", "controller",new { QueryString = 1}, FormMethod.Post, null))
{
}
Note : its due to passing wrong parameter in beginform constructor .
and in ur VIEW
#Html.Partial("~/Views/Shared/_x.cshtml")
With the help of several SO questions, I've figured out how to use two models on the same view, using the tuple form. At the top of my file is this:
#using Project.Models;
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
#model Tuple<Foo, Bar>
}
For the Foo stuff, it uses jQuery like this:
#Html.DisplayFor(tuple => tuple.Item1.ID)
and works fine. However, for my second model, it isn't displaying info, but is a submission form. Currently, this is what I have:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "createFoo", #action = "/api/Foo" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="editor-field">
#Html.TextAreaFor(tuple => tuple.Item2.Text)
#Html.ValidationMessageFor(tuple => tuple.Item2.Text)<br />
</div>
<input type="submit" value="Post Response" />
}
Mind you, this is mostly copy paste from other views since I'm new to MVC and it worked fine with other forms. For my FooController, I have this:
public void Post([FromBody] Foo foo)
{
Foo existingFoo = this.fooRepository.GetFoo(foo.ID);
if (existingFoo != null)
{
// throw error
}
else
{
System.Diagnostics.Debug.WriteLine("MESSAGE POSTING: " + foo.Text);
}
}
When submitting from the view, the received foo isn't null (checked in other tests), but the foo.text is empty. I've tried lots of different inputs and such, but I'm just so unfamiliar with the #Html.* functions and ASP.net-MVC in general that I'm not sure where I could be going wrong.
If you need to see my repository code let me know, but I doubt it'd have an effect on this. Thanks in advance for any help.
There are 2 issues I can see with your code above:
The way the Html helper will output your fields and how that feeds into your api post
Not having your ID in the controller.
1: Outputting a field like this (#Html.TextAreaFor(tuple => tuple.Item2.Text)) will give the field the name "Item2.Text". This is an issue as that is what gets passed on the post. You will get form data with Item2.Text:dfsdsgdfg. This won't match when your API controller tries to bind. So, try outputting the text field with a set name:
#Html.TextArea("Text", #Model.Item2.Text)
2: Your Id field is not in the form... thus it won't be sent. Try using a hidden field:
#Html.Hidden("ID", #Model.Item1.ID)
Also, just a clarification, this (#Html.DisplayFor(tuple => tuple.Item1.ID)) is not jQuery.
I'm trying to create a single view which allows the user to see the currently listed items using the index view model and then also allows the user to create a new item using a seperate create view model
So I've got two viewModels
-IndexFunkyThingsViewModel
-CreateFunkyThingViewModel
In essence I've got a main view:
#model IndexFunkyThingsViewModel
#foreach (var item in Model.FunkyThings)
{
/*Indexy stuff*/
}
/*If create item*/
#if (Model.CreateFunkyThing)
{
#Html.Partial("_CreateFunkyThingPartial", new CreateFunkyThingViewModel());
}
Then in my partial view I have
#model CreateFunkyThingViewModel
#using (Html.BeginForm(MVC.FunkyThings.CreateFunkyThing(Model)))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Create FunkyThing</legend>
#Html.EditorForModel();
<p>
<input type="submit" class="button green" value="CreateFunkyThing" />
</p>
</fieldset>
}
Finally in the controller I have:
[HttpPost]
public virtual ActionResult CreateFunkyThing(CreateFunkyThingViewModel createFunkyThingViewModel)
{
..
}
This all seems to compile happily and when I go to the view it works so far as displaying the create fields and such like. However when I then hit the submit button the controller receives no data. The ActionResult is called however in the debugger the createFunkyThingViewModel parameter is null when called by the submit button.
What am I doing wrong?
When posting to your controller, you're not sending the model down to it. Use this:
#using (Html.BeginForm("CreateFunkyThing", "ControllerName", FormMethod.Post))
then remove the p tags from around the button, and don't use anything with it.
The paragraph tags have a tendency to group the button separately from a form even if they are in the same outer container.
Suppose I have a simple search form with a textbox. And upon submitting the form I send the contents of the textbox to a stored procedure which returns to me the results. I want the results to be displayed on the same page the form was, except just below it.
Right now I'm doing the following but it's not working out exactly the way I want:
"Index" View of my SearchController
#using (Html.BeginForm("SearchResults", "Search", FormMethod.Post, new { #class = "searchform" }))`{
<fieldset>
<legend>Name</legend>
<div class="editor-label">
#Html.Label("Search")
</div>
<div class="editor-field">
#Html.TextBox("Name")
</div>
<input type="submit" value="Search" class="formbutton" />
</fieldset>
#{ Html.RenderPartial("SearchResults", null);
This is my "SearchResults" View:
#model IEnumerable<MyProject.Models.spSearchName_Result>
<table>
#foreach (var item in Model)
{
<tr>
<td>
#item.Name
</td>
</tr>
}
</table>
This is my Controller:
// GET: /Search/SearchResult
[HttpPost]
public ActionResult SearchResult(FormCollection collection)
{
var result = myentity.spSearchName(collection["Name"]);
return PartialView("SearchResults", result);
}
I can only seem to get the results to display on an entirely new page (not being embedded as a partial view), or I get an error when I load the search page because there are no results (since I hadn't searched yet).
Is there any better way to achieve what I'm trying to do? I feel like I'm going against some of the best practices in MVC.
You could return the results in a ViewData object then only show on the view it if is not null.
Very similar to this question MVC 3 form post and persisting model data
For this instance it looks like you are not passing the results to your partial view. Try this?
#{ Html.RenderPartial("SearchResults", Model.Results);
Since you are not persisting your search information using a model, the search information will be lost when the search form is posted.
Given your design and stated goal, it would be best to convert the form in your Index view into an Ajax form, then your controller can send your partial view back to populate a div below your Ajax form.
counsellorben