Category Archives: HTML

HTML

[RESOLVED]Re-using the same model, same controller with different views

I didn’t think that this was going to cause me so much difficulty .. and I have only just started with this project Surprised

I have one model which I want to populate the model’s properties over multiple views. I was planning on using the controller to determine which View should be displayed.

The model looks like this:

public class QC_Rework
{
    public int nViewToDisplay { get; set; }
    public int nReworkNumber { get; set; }
    public string cSecondaryReferenceType { get; set; }
    public string cSecondaryReferenceNumber { get; set; }
    public int nLineQuantity { get; set; }
}

My "Create" controller looks like this:

[HttpGet]
public ActionResult Create([Bind(Prefix = "ReworkNumber")] int ReworkNumber=0)
{

    var oQC = new QC_Rework();
    oQC.nReworkNumber = ReworkNumber;
    oQC.nViewToDisplay = 1;
    return View("GetSecondaryReferenceType2", oQC);

}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(QC_Rework oQC_Rework)
{
    // After GetSecondaryReferenceNumber2 the value of nViewToDisplay is "1"!!!
    // Even though the value in the Source Code and in the form says "2"!!!
    if (ModelState.IsValid)
    {
        switch (oQC_Rework.nViewToDisplay)
        {
            // Coming from Secondary Reference Type View
            case 1:
                if (String.IsNullOrEmpty(oQC_Rework.cSecondaryReferenceType) == true)
                {
                    ModelState.AddModelError("Model", "A secondary reference type needs to be selected!");
                    return View("GetSecondaryReferenceType2", oQC_Rework);
                }
                else
                {
                    oQC_Rework.nViewToDisplay = 2;
                    return View("GetSecondaryReferenceNumber2", oQC_Rework);

                }
            // Coming from Secondary Reference Type View
            case 2:
                {
                    oQC_Rework.nViewToDisplay = 3;
                    return View("GetQCDetails2", oQC_Rework);
                }
        }
    }
    // Should not get here at this stage!
    return View("NotFound", oQC_Rework);
}

The model’sproperty nViewToDisplay controls which Views get displayed.

When I debug the code, before the View GetSecondaryReferenceNumber2 gets called, the value in oQC_Rework.nViewToDisplay is set to 2 … but in the view itself it is "1′!!

What am I doing wrong?

Many thanks …

you don’t show the view code, but most likely its something like:

   @Html.HiddenFor(m=>m.nViewToDisplay)

with the html helpers, the lambda expression is just to get the name. ("nViewToDisplay") in your case. this name is then used to lookup the value. The postback form collection is searched before the ViewBag.Model (where you changed the data). so the postback
value is used.

just use a vanilla hidden field:

  <input type="hidden" name="nViewToDisplay" value="@Model.ViewBag.nViewToDisplay" />

or original helper that takes the value

   @Html.Hidden("nViewToDisplay",ViewBag.nViewToDisplay)

The type or namespace name 'WebGrid' could not be found (are you missing a using directive or an assembly reference?)

i am getting this kind of error message while running the programm as compilation error. previously i didn’t get this kind of error message but suddenly i am getting the error. 

previously in all modules it’s working fine but suddenly in all the modules i am getting the same error. 

what’s problem behind on this

Hi,

did you uninstall / update a nuget package related to System.Web.Helpers?

Grz, Kris.

no i didn’t uninstall any package but in references i have this System.Web.Helpers

Hi,

do you have a CVS ready so that you can go back in history of your code to a state where it worked? If so check the differences. Likely some using statement got lost.

Grz, Kris.

Hi,

You may not have "WebGrid.*.dll" with your project, or you may update your project, and "WebGrid.*.dll" is incompatible. Or accidentally deleted from your project dll libs.

You may need to add reference again to your project.

Please check carefully and Have fun

i was installed the webgridmvc from nuget also but it is not working

Hi,

Make sure that name is "WebGrid" or "WebGridMVC". It is case sensitive. Please check.

I’ll try to test it and come to you then.

WebGrid grid = new WebGrid();

i am using this thing only from the entire project upto few days back also it’s working fine. right now we are trying to add a new view with the webgrid then we are getting this

problem and we run the entire project which have this webgrid all are getting the same error. we shocked what happend and how to regetting the Webgrid we dont want to change any other things right now because i have so many forms this webgrid

Hi,

If you install webgridmvc, you must use "@using WebGridMvc;" for the nameSpace.

Please post the detail errors.

if i changed to WebgridMvc then i have to change my entire code where i have this webgrid this will again long time taken thing 

 Layout = "~/Views/Shared/_AdminLayout.cshtml";
Line 5:  
Line 6:      WebGrid grid = new WebGrid();
Line 7:      grid.Bind(Model,
Line 8:                autoSortAndPage: true

CS0246: The type or namespace name ‘WebGrid’ could not be found (are you missing a using directive or an assembly reference?)

this error i am getting when i run the page 

Are you using the appropriate @using statement?  If so, is it at the top of the page or the web.config file?  If it is in the web.config then try closing VisualStudio then re-opening it as that config setting isn’t dynamically processed as you change it. 
Also check the appropriate dll is in the bin folder.  Something else you can test to see if it is a missing assembly or missing "using" is to use the full classname, eg the namespace and classname, and see if the class is found then.

the problem is solved after remove the System.Web.Helpers from the references and add it again. But i got another problem while do it when  i tried to run the program i am getting the following error

An exception of type ‘System.TypeLoadException’ occurred in Microsoft.Owin.Security.Cookies.dll but was not handled in user code

Additional information: Could not load type ‘Microsoft.Owin.Security.AuthenticationDescription’ from assembly ‘Microsoft.Owin, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′.

Hi Siva_540,

Thanks for your post.

Siva_540

Additional information: Could not load type ‘Microsoft.Owin.Security.AuthenticationDescription’ from assembly ‘Microsoft.Owin, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′.

You can try install the package from Manage NuGet packages

Microsoft.Owin.Security

Hope this can be helpful.

Best Regards,

Eileen

i have already this in my project

[RESOLVED]Not able to get name of the image button on Controller side

Hello There, 

I am new to MVC and facing lot of issues :(

I have one image, acting as a button, when I clicked on it, it post back, but not able to find its name in Action. Here is my code snippet

View :-

@using (Html.BeginForm())
{

<input type="image" value="AddRoutine" name="button" src="~/Images/Add.png" id="imgAdd" title="Add" alt="Add" />

}

Controller :- 

[HttpPost]
public ActionResult Index(string button)
{
          // the parameter "button" is always comes null 

it is working fine when I use input type button instead of image 

Where I am doing mistake, what is the problem with input type image ?

Please help me out 

Thanks
Ash

An input type="image" is not an input that can carry a value to the server

try this

<button type="submit" value="AddRoutine" name="button" >
	
    <img src="~/Images/Add.png"  title="Add" alt="Add"/>
	
</button>

thats because the image posts two values containing the x & y positions. name.x and name.y. so you need an object:

public class ImageValue
{
   public int x {get; set;}
   public int y {get; set;}
}

[HttpPost]
public ActionResult Index(ImageValue button)
{

} 

[RESOLVED]Html.Helpers or Html tags ?

When we are developing our views, we can set codes as HTML.Helpers or write them as HTML tags.
However what’s best ?

EXAMPLE: CREATING A HYPERLINK

1. @Html.ActionLink("About this Website", "About")

2. <a href="/Home/About">About this Website</a>

a) So what should I use ? Should I write the HTML tags directly without razor or use helpers ?
b) If I use helperss would it cause an extra processing once I have to convert Razor to HTML ?

You can choose either. I personally use both, depending to where I’m linking.

For members and registered users, on an ASP.net project, I usually use the helpers, and on any pages accessible to unauthenticated users I use the <a href=""></a> tags.

If you use the Html.ActionLink helper, the url will always be constructed properly regardless of changes in the hosting environment, or changes between development, testing and production environments. This might not be an issue to you in which case feel
free to hard code your links. 

I have full control over my hosting environment and make sure that the development environment mirrors it as much as possible. Despite that, I use the helpers just in case. 

aganeto

If I use helperss would it cause an extra processing once I have to convert Razor to HTML ?

Yes, but it is so insignificant that if you have to worry about it, you have much bigger problems.

Webgrid Questions

I am wanting to create a webpage that has a webgrid where you can select a row and it will show the details of that row below the webgrid for editing. Could someone provide an example of how to do this?

I wrote and article about doing this using the Web Pages framework. You can adapt it to MVC: http://www.mikesdotnetting.com/Article/168/The-WebGrid-Helper-Making-Selections

Thank you for the reply. I found that article very helpful. Except when you got to this part:

@if(grid.HasSelection){
    var book = grid.SelectedRow;
    @RenderPage("~/Partials/EditBook.cshtml", new { Book = book } )
}

How did you get the value for book? I do not see anywhere in the code you gave where that is located. 

The second parameter of the RenderPage method takes an anonymous object representing data to be passed to the partial. In this case, the value (book, with a lower case b) is the SelectedRow property of the grid. The SelectedRow property is a dynamic
object whose properties are made up from the column names. So book is a dynamic object with BookId, Title, Description etc properties.  This is passed to the Partial’s
PageData property (also accessible via the dynamic Page property). So in the partial, the Id of the book is obtained like this:

var bookid = Page.Book.BookId;

Thank you for the response. Sorry for my delayed response. But I am trying to do this in a MVC format, so I would not want to access the data from a webpage. How do you pass that value to a controller to then access the data?

You still need to pass the data to the View. In MVC, you get the data within the controller and pass it to the view either as a strongly typed model or in ViewBag. Then you will bind the model to the WebGrid in the View. 

I am trying your method and actually querying the database from the partial view but I am using Entity Framework to access the database and I do not have the functionality do the Database.Open command. Again is there a way to pass the selected value from
the webgrid to my controller and then render that partial page by a strongly typed Edit page?

Partial View won't Render List from Database

I have been battling this all day.  Thanks to JohnLocke that I have gotten this far.  I am rendering a Partial View with the Following:

        @Html.Action("GetComments", "LoanApplication")

The partial looks like this:

  @model Portal.ViewModel.Comments.LoanApplicationCommentsViewModel


  @foreach(var item in Model.Comments)
            {
                @item.Comment
            }

The Controller Action looks like this:

[HttpGet]
        [Route("GetComments")]
        public async Task<ActionResult> GetComments()
        {
            var loanApplicationServiceProxy = base.ServiceProvider.LoanApplicationServiceProxy;

            var comments = await loanApplicationServiceProxy.GetLoanApplicationCommentsByLoanApplicationIdAsync(loanApplicationId) ?? new List<LoanApplicationComment>();
            
            var commentsList = new LoanApplicationCommentsViewModel()
            {
                Comments = comments                }
            };
    return PartialView("_CommentsView", commentsList);

Here’s the problem…although the "list" is not empty when the Partial View tries to render it throws an error.  However, if I use the EXACT same code in a Main view, the list is displayed.  The other twist is that if I change the above code to "hardcode"
a comment (like the example below), the Partial displays fine.  What am I missing here?  I’m pulling my hair out.  ANY and ALL assistance is appreciated!

The code below works for the partial (the only difference is that the list is hardcoded).

            var commentsList = new LoanApplicationCommentsViewModel()
            {
                Comments = new List<LoanApplicationComment>{
                    new LoanApplicationComment{
                        Id = Guid.NewGuid(),
                        Comment = "This is a Test Comment",
                        CreatedBy = Guid.NewGuid(),
                        CreatedDate = DateTime.Now,
                        LoanApplicationId = loanApplicationId
                    }
                }
            };
    
            return PartialView("_CommentsView", commentsList);

what is the variable "loanApplicationId" in this line?

var comments = await loanApplicationServiceProxy.GetLoanApplicationCommentsByLoanApplicationIdAsync(loanApplicationId) ?? new List<LoanApplicationComment>();

Its a Guid.  I have it hardcoded in at the top with private readonly Guid loanApplicationId = new Guid("blah-blah-blah").  It’s a real Guid pointing to a real record.  I did figure out that it does NOT like the await, but everything in the project (which
I didn’t create) is all asynchronous calls.  Even if a hardcode the "new" comment, if I don’t comment out the above line, the @Html.Action on the Partial throws an error.

Getting data of json array

I create an array with javascript that has some ids. I pass them back to my controller like so

$.ajax(
{
url: "/Home/GetChildKeys",
data: { ids: nodeKeys },
dataType: "json",
type: "GET"
}).done(function (result) { });

What I’m not sure on is how I get that data in my c# code to work with it. Here’s my function in my controller

//how do I get the array passed in as an argument
        [HttpGet]
        public JsonResult GetChildKeys(object var)
        {
            //need to figure out how to read id data and then pass back child keys
            return Json("foobar", JsonRequestBehavior.AllowGet);
        }

The param you choose for your ‘data’ option in the ajax-request must match the param of your post-action. 

[HttpGet]
public JsonResult GetChildKeys(someType ids)
{
...

Is nodeKeys a list of objects, or a string?  That will determine the "someType" above

I knew I’d have to get the type, I just wasn’t for sure what type it would be.

nodeKeys is just a javascript string array;

Something like 

var nodeKeys = ["cat_1", "cat_2", "cat_3"];

That’s not json, but anyway, try

string[] ids

or

List<string> ids

Then you could do

[HttpGet]
public JsonResult GetChildKeys(string[] ids)
{
foreach (var id in ids)
{
// process each id here
}

...
}

I was under the impression if I sent the data like this (underlined in bold)

$.ajax(
{
url: "/Home/GetChildKeys",
data: { ids: nodeKeys },
dataType: "json",
type: "GET"
}).done(function (result) { });

that it would convert that to json for me?

The "data" node will be json, but the data you are passing in the "ids" property is just a plain javascript array.

hi,

usually ajax communication more serialized content, while receiving  action method have to serialise as per mention data type, 

client : var array1 = ["A", "B", "C", "D"];
server : public JsonResult AjaxCallTest(List<string> postedModel){ //code…… }

client : var array = [1, 2, 3, 4, 5];
server : public JsonResult AjaxCallTest(List<string> postedModel){ //code….. }

or just pass json string, then in controller action have to parse posted json to respective model object.

Ref : serializing and deserializing json in c#

Thanks,

Jai

So how do I go about passing that array back to my application?

Basically, there’s some code that runs through a treeview and pulls the ids of any checked items and pushes them into the array. So, I need to send that array of ids back to my controller as json data. I don’t really care how they get there, array, list,
etc. but I just need to be able to loop through them. Ideas?

hi,

Client :

var selectedItems = [1, 2, 3, 4, 5]; // try to push your selected item.

$.ajax({
url: "/Account/AjaxCallTest/", //your url
traditional: true,
dataType: "json",
type:’post’,
data: { ids : selectedItems },
success:function(data) { 
},
error: function (errorMsg) {
}
});

Server:

[HttpPost]
public JsonResult AjaxCallTest(List<int> ids )
{
// your logic…
}

Thanks,

Jai.

That’s what I tried after your first post with no luck. This is what I have

var nodeKeys = ["cat_1", "cat_2", "cat_3"];

$.ajax(
{
url: "/Home/GetChildKeys",
data: { ids: nodeKeys },
dataType: "json",
type: "GET"
}).done(function (result) { });

C# 

        //how do I get the array passed in as an argument
        [HttpGet]
        public JsonResult GetChildKeys(List<string> ids)
        {
            //ids is still null
            var foo = ids;

            //need to figure out how to read id data and then pass back child keys
            return Json("foobar", JsonRequestBehavior.AllowGet);
        }

http://forums.asp.net/t/1934215.aspx?Using+jQuery+ajax+to+call+asmx+webservice+methods

either add

contentType:
"application/x-www-form-urlencoded; charset=UTF-8",

to your $.ajax call, or try

data: JSON.stringify({ ids: nodeKeys }),

I’ve tried both of those and ids is still null

nodeKeys = ["cat_1", "cat_2", "cat_3"];
$.ajax(
{
url: "/Home/GetChildKeys",
data: JSON.stringify({ ids: nodeKeys }),
dataType: "json",
type: "GET"
}).done(function (result) { });

and even

nodeString = "cat_1,cat_2,cat_3";
$.ajax(
{
url: "/Home/GetChildKeys",
data: "{keys: ‘" + nodeString + "’}",
dataType: "json",
type: "GET"
}).done(function (result) { });

You have to set the correct contentType too so the service knows how to interpret the data you are sending.  As well as the link I posted with all the examples, look at this to see how you can use the browser’s dev tools to see what is being sent and what
the response is.

http://forums.asp.net/t/1982579.aspx?Using+the+browser+s+dev+tools+to+diagnose+ajax+problems+and+other+things+

[RESOLVED]Issue with Razor and VB.net Supplying a default value

I have been able to do this with C# but with VB.net in the view I am having issues with syntax.

C# works great:
@Html.TextBoxFor(model => model.Address, new { @class="BTCaddress", @Value="" + ViewBag.Address + "" })

Not sure how to format in VB.net? I also have issues getting it to work with EditorFor:

Regular scaffolded code:
@Html.EditorFor(Function(model) model.Company, New With {.htmlAttributes = New With {.class = "form-control"}})

What I have tried:
@Html.EditorFor(Function(model) model.Company, New With {.htmlAttributes = New With {.class = "form-control", @Value="" & @ViewBag.Company & "" }})

Should I be using TextboxFor  in VB.net for this and how would I format it?

Hi,

Based on my test in the MVC 5 project, I found that we can’t set the default value by specify the data to the value.

For the Html.XXFor method, the default value should be based on the field value of Model. So, you need to create an instance with the default value and return to the view. You also could use
Html.TextBox method.

belcherman

@Html.TextBoxFor(model => model.Address, new { @class="BTCaddress", @Value="" + ViewBag.Address + "" })

Not sure how to format in VB.net? I also have issues getting it to work with EditorFor:

The VB code should be:

@Html.TextBoxFor(Function(m) m.Address, New With {.class = "BTCaddress",.value=ViewBag.Address})

Best Regards

Starain Chen